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:

System.Nullable<int> nullableInt = null;

An even simpler way of doing this is by doing the following:

int? nullableInt = null;

By proceeding the variable type with a question mark, the compiler will know that you mean for the type to be nullable. Neat!

Two useful properties of nullable value types are the Value and HasValue properties. Value, is, of course, the value of the variable, whereas HasValue returns a boolean which indicates whether or not the variable has been given a value yet.

Also worth noting is that the compiler will prevent you from assigning a nullable value type variable to a non-nullable value type variable. For example, the code below will not compile:

int? nullable = 1;
int nonnullable = nullable;

However, the following will compile:

int? nullable = 1;
int nonnullable = nullable.Value;

BUT, if the value of a nullable value type variable is null, and you attempt to assign the value to a non-nullable value type variable, you'll get a runtime error. Make sure you check the HasValue property of your nullable value type variables before you attempt to assign their values to standard value type variables.


Popular Posts

How To Mock Out Child Components In Unit Tests of Angular 2 Code

A Generic Method Using HttpClient to Make a Synchronous Get Request

The Cause and Solution for the "System.Runtime.Serialization.InvalidDataContractException: Type 'System.Threading.Tasks.Task`1[YourTypeHere]' cannot be serialized." Exception

Unit Testing with a Mock Entity Framework DbContext and Fake DbSets

A Red Herring When Using Moq to Mock Methods With Optional Parameters