Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does the ? operator mean in C# after a type declaration?

Tags:

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?

like image 424
user2425056 Avatar asked May 27 '13 13:05

user2425056


1 Answers

? 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
like image 50
Habib Avatar answered Oct 01 '22 16:10

Habib