Tom Goff's .Net Musings

Tidbits of information regarding .Net, C#, and SQL Server.

COTW: Nullable Generic Structure

leave a comment »

The Nullable Generic Structure[^] allows developers to wrap value types so that they can be set to null. This wrapper object can either hold the referenced value type or it can indicate that no value is referenced (e.g. it’s null).

For example, if you would like to have an integer value that can also be set to null, you can define a variable as shown below:

Nullable<Int32> i = null;

if (null == i)

    i = 8;

When assigning a value to the Nullable variable, an implicit conversion is provided from the wrapped type. In our example above, this means that we can directly assign the value 8 without casting it. In addition, if we had an variable of type Int32, then we could directly assign it to the Nullable variable as shown here:

Int32 i1 = 8;

Nullable<Int32> i2 = i1;

When getting the actual value out of a Nullable variable, then we have to explicitly convert to the wrapped type as shown here:

Nullable<Int32> i1 = 8;

Int32 i2 = (Int32)i1;

In addition, you can access the Value[^] property directly. In both cases, an InvalidOperationException[^] will be thrown if there is no value (e.g. it’s null).

To determine if a value is present (e.g. it’s not null), then you can either compare the Nullable variable with null, as shown in the first example, or you can check the HasValue[^] property.

There is a helper method called GetValueOrDefault[^] which allows you to get the associated value or, if there is no value, then return a default value. So the following code, can be reduced to a single line:

Nullable<Int32> i1 = 8;

// ...

Int32 i2 = 99; // 99 is our default value

if (null != i1)

    i2 = (Int32)i1;

// ... The code above can be reduced to

Int32 i3 = i1.GetValueOrDefault(99);

Finally, C# compiler has a syntax shortcut to quickly and easy create Nullable objects. The code below actually uses the Nullable structure:

// The following two lines create identical objects

Nullable<Int32> i1 = 8;

Int32? i2 = 8;

You can find more information on MSDN[^] or Google[^].


Written by Tom

September 30, 2007 at 4:17 pm

Posted in .Net, C#, Class of the Week

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: