C# Tutorial Lesson 25: Nullable Types [2.0]

Note: this lesson covers new functionality in C# 2.0, which at the time of writing is not released.

C# now supports 'nullable' types: value types which are able to take the value 'null'. The reported reason for this change is to make it easier to integrate with databases, which may hold null values in fields of any type.

The new nullable types are constructed using the ? symbol. For instance,


is the new, nullable form of int. It is generally equivalent to int, except that it can take the value null and has two associated properties: Value and HasValue. When the int? type is non-null, the HasValue property is set to true and the Value property contains an int with the numeric value. When HasValue is set to false, on the other hand, the Value property is not available; an attempt to access it throws an exception.

In many cases there are implicit conversions between nullable types and the types on which they are based. Furthermore, the various standard operators (such as addition, etc.) work as one would expect.

The 'null coalescing operator'

A new operator has been introduced, consisting of two question marks, viz:


The effect of this operator in

x ?? y

is to return x except where x is null, in which case it returns y. So, for instance

int z = x ?? 0

always sets z to an integer value, which is zero when x is null. This new operator can also be used on reference types.

Link Building Information