Handling nullable value types in .NET 1.x

One of the great new features in .NET 2.0 is support for nullable types – especially important when dealing with value types such as Int or DateTime values coming from a database. Previously you were forced to either set and track another binary flag or to use a “special” value to represent null that sooner or later would turn up in real data.

In C# 2.0 thanks to a bit of syntactic sugar we can do this;

int? nullable1 = 1;
if (nullable1 == null) nullable1 = 2;

Which the C# compiler actually turns into the following:

Nullable<int> nullable1 = new Nullable<int>(1);
if (!nullable1.HasValue) nullable1 = new Nullable<int>(2);

This makes use of the new Nullable generic structure to wrap the value with an additional boolean HasValue property.

That looks surprisingly similar to the syntax of the open-source NullableTypes project you can use with .NET 1.1 (or 2.0):

NullableInt32 nullable1 = new NullableInt32(1);
if (nullable1.IsNull) nullable1 = new NullableInt(2);

Disclaimer: I’ve worked on the NullableTypes project specifically implementing the IXmlSerializable, NullableGuid & NullableTimeSpan.

[)amien

Respond to this