C# Nullable – Understanding ? Operator after Type Declaration in C#

c++nullable

I have some C# code with the following array declaration. Note the single ? after Color.

private Color?[,] scratch;

In my investigating I have found that if you you have code such as:

int? a;

The variable a is not initialized. When and where would you use this?

Best Answer

? is just syntactic sugar, it means that the field is Nullable. It is actually short for Nullable<T>.

In C# and Visual Basic, you mark a value type as nullable by using the ? notation after the value type. For example, int? in C# or Integer? in Visual Basic declares an integer value type that can be assigned null.

You can't assign null to value types, int being a value type can't hold null value, int? on the other hand can store null value.

Same is the case with Color, since it is a structure (thus value type) and it can't hold null values, with Color?[,] you are making an array of nullable Color.

For your question:

The variable 'a' is not initialized. When and where would you use this?

By using ? with variable doesn't make it initialized with null or any other value, it is still has to be initialized.

int? a = null; 

int b = null;//error since b is not nullable
Related Question