Monday, October 6, 2008

Fun with C# 3.0 (#4) - Nullable types and the ?? operator

C# has reference types and value types. Reference types are commonly called objects, and variables that are declared to be of a reference type can refer to an object or be null. Value types (int or bool, for example) can be stored in variables that contain the actual value, and therefore can never be null.

Sometimes it is useful to have a value type that can have a null value, so this feature has been added to C# 3.0.

This feature is implemented using generics and the type System.Nullable<T>, the shorthand for which is T?. The property HasValue can be used to see if the variable is null. Here's an example:

int? x = 10;
if (x.HasValue)

A nullable type can not be assigned to a value type. The following will not compile:

int? x = 10;
int y;
y = x;

Rather use the Value property:

int? x = 10;
int y;
y = x.Value;

Accessing Value will throw an InvalidOperationException if the nullable type is null. Use the ?? to assign a default value.

int? x = null;
int y;
y = x ?? 0;

This is equivalent to:

y = x.HasValue ? x.Value : 0;

Usage of the ?? operator is not limited to Nullable types. For example:

string name = enteredName ?? "Name not entered.";


Anonymous said...

Wasn't theese features added in C# 2.0??

Ray Henry said...


You are correct. I wasn't aware of them and assumed they were added recently.