Sunday, 28 January 2007

Nullable Types

Conventially it was not possible to set a System.ValueType to null, when the Constructor runs it defaults the value of a System.ValueType. Typically this does not cause a problem until you start interacting with a database for example, which does allow nulls. When this happens I have conventially used code like the following to determine whether a System.ValueType has a value or not.


if (myInt != int.MinValue)
{
// Int has been set.

}
if (myDateTime !=
DateTime.MinValue)
{
// DateTime has been set.

}
An alternative now exists with nullable types, nullable types are instances of the System.Nullable struct. A nullable type can represent the normal range of values for its underlying type, plus an additional null value. How to declare nullable type of type Int32, both of the following declarations compile to the same IL code.


int? a = null;
Nullable
<int> a = null;
You can determine whether a nullable type has a value by using the HasValue property, you can also return the value using the Value property if no value is assigned calling this method will result in a System.InvalidOperationException.

If you wish to default the value of a nullable type when reading its value you can use the null coalescing operator, this can also be used with value types.


int? a = null;
Console.WriteLine(a
?? -1);
The code above defaults the value of a when null to -1, which is very like the statement below but a great deal neater.

int? a = null;
Console.WriteLine(a
== null ? -1 : a);

No comments: