Nullable Types

1 minute read

A common problem that developers run into with .NET v1.1 is the situation where you want a value type such as an int or bool but you want to allow for the value to also be undefined or null. For example, data coming from a database might not have a value define for one of the fields. The .NET Framework has had special SQL data types to deal with this issue but what if your problem domain isn’t related to SQL?

In .NET 2.0, there is a new generic type System.Nullable that allows you to represent a value that can also be null. The T stands for the specific type you want to use so your code might use System.Nullable or System.Nullable or even System.Nullable. C# has a special syntax that maps T? to System.Nullable so you can add a question mark to your value types and they become "nullable". The following two lines are equivalent:

System.Nullable<bool> myNullableBool = false;
bool? myNullableBool = false;

As ever, C# tries to take the typing out of writing code.

The following code sample shows nullable types in use:

class App {
    static void Main() {
        int? i = 1;
        System.Console.WriteLine("i = {0} ({1})",i,i.HasValue);
        i = null;
        System.Console.WriteLine("i = {0} ({1})",i,i.HasValue);
    }
}

This generates the following output:

i = 1 (True)
i = (False)

Nullable types are only meaningful with value types. string? won’t work because you can already set a string variable to be null.

Updated: