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.

Comments

Popular Posts

Resolving the "n timer(s) still in the queue" Error In Angular Unit Tests

How to Get Norton Security Suite Firewall to Allow Remote Desktop Connections in Windows

How to Determine if a Column Exists in a DataReader

Fixing the "Please add a @Pipe/@Directive/@Component annotation" Error In An Angular App After Upgrading to webpack 4

Silent Renew and the "login_required" Error When Using oidc-client