I was reading about
Nullable Types in the
C# 2.0 specification for the
.NET Framework 2.0 today. I am surprised I didn't find out about this
feature long ago, goes to show that you learn something new every day.
So what are Nullable Types?
Simply put, Nullable Types are value types that a can be assigned null. The following line of C# will give you a compiler error:
A System.Int32 is not a reference type (it is a value type), and can
therefore not be assigned a null value, however, the next line of code
will compile under the 2.0 framework:
Adding a question mark after the type turns the System.Int32 value type
into a Nullable Type. The line above, is in fact, shorthand for the line
below:
The
System.Nullable<T> generic class is used to create value type variables that contain an undefined state. The
HasValue property of this class will return true if the contained variable has an assigned value, or false if it null. The
Value property will return the value of the property, or throw a
System.InvalidOperationException if the contained variable is unassigned.
Why use Nullable Types?
How many times have you defined an integer in your code, and assigned it to -1 in the constructor (or definition) as meaning
undefined?
What happens of your code needs to change to allow negative numbers,
but you still need to determine if a value has been assigned to your
variable? With Nullable Types, you can assign null to your
variable and test to see if the variable has been assigned at runtime.
I am presently writing a piece of code that uses reflection to get a
list of properties in a class, and then output an XML tag for each
property if the property value is not null. Using Nullable
Types, I do not have to worry about value types outputting if their
value has not been assigned.
Casting from Nullable Type to value type. The following lines of code will fail compilation
The following will compile, but throw an exception if y is null:
The following will also compile, but throw an exception if y is null:
What is needed in the above examples, is an operator that will assign a
default value if the nullable variable type is unassigned. It
just so happens that one exists. The following line will assign -1 to x
if y is null:
Nullable types work fine with most of the basic operators,
bool& is an interesting one. The table below defines how logical and and logical or work with two boolean nullable types:
x | y | x&y | x|y |
|---|
true | true | true | true |
true | false | false | true |
true | null | null | true |
false | true | false | true |
false | false | false | false |
false | null | false | null |
null | true | null | true |
null | false | false | null |
null | null | null | null |
So what are you waiting for? It's time to start using the .NET
Framework 2.0, with it's array of nice new features, including Nullable
Types.