SYSK 24: ?? operator. Is it new to you?

Did you know that C# now has a new operator ?? ?   It has to do with the support for nullable data types.  A nullable type can contain a value, or it can be undefined. The ?? operator defines the default value to be returned when a nullable type is assigned to a non-nullable type. If you try to assign a nullable type to a non-nullable type without using the ?? operator, you will generate a compile-time error. If you use a cast, and the nullable type is currently undefined, an InvalidOperationException exception will be thrown.

For example:

// define a nullable integer
int? x = null;

// Now assign it to a not nullable integer avoiding the errors
// y = x, unless x is null, in which case y = -1.
int y = x ?? -1;

For more information, see Nullable Types (C# Programming Guide).

Reference:  ms-help://MS.VSCC.v80/MS.MSDN.v80/MS.VisualStudio.v80.en/dv_csref/html/088b1f0d-c1af-4fe1-b4b8-196fd5ea9132.htm

Skip to main content