Operator? when writing data types

6

I have a curiosity and I want to get rid of the doubt, in which cases a variable is declared in the following way:

public short? Secuendia {get; set;}

What does the question mark mean and in which cases the data type is accompanied by a character ?

    
asked by Pedro Ávila 01.04.2016 в 00:18
source

2 answers

7

The declaration type ? is used when you use a data type that can not be null for example a Structure and you force it to be null , this is achieved by dialing with the operator ?

This is called Nullable

You can check more here: Operator ??

Difference against a normal declaration

int a;
int? b;

a = 5;//ok
b = 5;//ok

a = null; //Error: Cannot convert null to 'int' because it is a non-nullable value type
b = null;//ok
    
answered by 01.04.2016 / 00:26
source
7

The ? character is used in types of to indicate the value is nulleable , so it can be a valid number or it can be null.

Known as Nullable Types , and may represent the normal range of numbers of the specific type plus the null value.

In practice they are instances of the structure System.Nullable<T> therefore it has some methods.

Example:

int? num = null;

// tiene valor en num
if (num.HasValue)
{
    System.Console.WriteLine("num = " + num.Value);
}
else
{
    System.Console.WriteLine("num = Null");
}

In Boolean it is used to represent tristate or three-state values.

bool? tristate; // puede ser true, false o null
    
answered by 01.04.2016 в 00:20