Showing posts from June, 2008

Using Nullable Value Types in .NET 2.0 and Higher

In .NET, there are two types of variables: value types and reference types. Values types are generally allocated on a thread's stack, whereas reference types are allocated from the managed heap, and have values which are the addresses of the memory location where the object resides.

The default value of a reference type variable is null, but a value type can't be null -- it's default value will be a value that correspond's to the variable's type (for example, the default value of an int is zero). But what if you don't want a default value for a value type? In .NET 1.x, you're out of luck, but in .NET 2.0 and higher, you can use a nullable value type, made possible through the magic of generics.

To create a nullable value-type variable, use the System.NUllable<T> generic type definition, where T is the type of variable you want to instantiate. For example, the following line creates a nullable integer type and assigns it a null value: