Nullable Types in C#

2007, Aug 14    

In .NET 1.0 and 1.1, if you wanted to store a null value for a value type (int, double, DateTime, etc) you would have to box it or write your own wrapper around it. The introduction of generics in .NET 2.0 allowed the concept of nullable types to be introduced into the language through the Nullable</strong> structure.</p>

Now if you want an int value that could be null, you could write,

Nullable<int> x = new Nullable<int>( 12 );

This is a fair amount of typing, so luckily, there is compiler support for nullable types using the ? operator.

int? y = null;
int? z = 14;

You can test if a value is null with the HasValue property, or you can simply compare to null.

if ( x.HasValue )
    // ...
if ( y == null )
    // ...

You can add two nullable types together and they will preserve the null values.

int? i = x + y; // i == null
int? j = x + z; // j == 26

To assign a nullable type back to a value type, you use the Value property.

int k = j.Value;

The only problem with the above is that it will throw an exception if the value is null. To get around this, always check for null first, or use the GetValueOrDefault method.

int l = i.GetValueOrDefault(); // l == 0
int m = i.GetValueOrDefault( -1 ); // m == -1;

Nullable types are fairly simple, but really powerful when you need them. Make sure they are in your tool belt.