We have always enjoyed the ability of setting reference types to null (Nothing in VB) from the early days of C# and VB, however this feature has been missing from the value types like Boolean and DateTime.
// Perfectly valid.
DataSet customerDS = null;
// Compile-time error, null cannot be converted to DateTime
DateTime dateOfBirth= null;
One solution is to use default values (e.g. 01/01/01 for dates, 0 for Integers and false for Boolean), but this may not be desirable because of inconsistency between the default values for various value types. Also in some scenarios we want to make a difference between having the default value and having no value.
Another solution is to define our own structs to wrap the primitive value type as well as a null value. But in order to get strong typing we need to define one struct for every value type that we use.
.NET 2.0 allow us to create a generic type that adds "null" to the range of a value type. For example:
public
struct MyNullableType<AnyPrimitiveType>
{
public AnyPrimitiveType value;
public bool IsNull;
}
So in our program we could write:
MyNullableType<DateTime> DateOfBirth;
DateOfBirth.IsNull = true;
Since we are using Generics, we get the type safety and we should define the nullable class only once. But the problem is that the syntax is not particularly interesting. The good news is that nullable type functionality is now baked into the .NET Framework 2.0 so there is no need to write our own class and we get a nice langauge support too.
The BCL provides us with a generic type named System.Nullable (struct), which accepts a value type as its generic type (reference types are nullable by design).
namespace System
{
public struct Nullable<T> where T : struct
{
public T value;
public bool HasValue;
}
}
It also provides us with a shorthand syntax, so instead of:
public System.Nullable<DateTime> DateOfBirth = null ;
we can write:
public
DateTime? DateOfBirth = null;
And the compiler will take care of the rest for us.
Apart from the System.Nullable struct, it also defines the (static) Nullable class, which provides more features like obtaining the type of the underlying value of a nullable type. Eric Gunnerson has more on this subject.