Nullable Types in C#

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<t> structure.

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

Nullable x = new Nullable( 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.

4 thoughts on “Nullable Types in C#

  1. Actually, ?? works on any reference or Nullable type.

    For example,

    string IamNull = null;
    string nonNull = “foo”;
    string s = IamNull ?? nonNull;

    s gets set to nonNull

  2. Don’t forget the ?? shortcut for GetValueOrDefault

    int m = i ?? 0;

    m will have the value 0 if i is null, or i if it is not null.

  3. You don’t have to use the .HasValue property. The compiler is smart enough to figure out what you mean if you say something like

    int? i = 5;
    if(i != null)
    // use it here

Comments are closed.