How to use ?? Operator in C# to assign a nullable type to a non nullable type?

Code example

int? nullableInt = null;
 int nonNullableInt = nullInt ?? 0;
 //sets the nullableInt's value to the nonNullableInt 
 // only when it has a value, else it will set 0.
 //in our case it will assign 0
 Console.WriteLine(notNullInt);
 //prints 0

This ?? operator can be used to save code that will test for null and then we will set the value.

Advertisements