C# 2.0 Nullable Type Goodness
One of the first new features I used in .NET 2.0 (or, more specifically, C# 2.0) was that of Nullable Types. Pre-C# 2.0, value types could not be assigned a null value. This is fair enough, since this behaviour is by design and a technical construct of the language and CLR. However, for people like myself, whom are very particular about their classes internally (object initialisation, etc), it is quite frustrating.
Pre-C# 2.0: Value Initialisation
If I have a class with Boolean and integer internal fields, I would be forced to initialise them with an explicit value, as shown below:
// Assign -1 as an initial value private int _x = -1; // Assign either true or false as an initial value private bool _y = false; // Assign null as an initial value private string _z = null;
In the first two examples, there is no option but to assign an explicit value. This could be considered bad programming practice by many; and is potentially errorneous since we are assigning values to an object that, as far as the class is concerned, is not yet initialised. If these values are somehow examined and used, it could result in a buggy application.
C# 2.0 introduces Nullable Types. That is, equivalents of value types that can be assigned a null value. They’re extremely simple to use, with a question mark character appended to the type keyword to indicate it is a nullable version of the type.
So, the example given in the previous section would look like this:
// Assign null as an initial value private int? _x = null; // Assign null as an initial value private bool? _y = null; // Assign null as an initial value (as before) private string _z = null;
This looks much better. Better programming practice, and no explicit initialised values that might cause bugs later. Of course, if you use them with their original [non-nullable] value-type counterparts, you must cast them:
bool? x = null; bool y = false; x = (bool?)y;
This is understandable, since by definition they are not the same type of object. Just remember to check you never assign null to a non-Nullable Type:
// Wrong - will throw an exception y = (bool)x; // Better - check it first if (x.HasValue) { y = (bool)x; }
In the first example, x is null, so it cannot be assigned to y (and the operation would generate an exception). In the second example, the HasValue property is being used to check for a value first (it is not null). The assignment only takes place if this is true.
There are many other rules and conditions surrounding the use of Nullable Types, and I encourage you to take a look at the MSDN documentation in order to make the most of them. The page also gives details of how it works at a low level, which is quite interesting.
Thank you Microsoft for this feature. You’ve made a perfectionist developer very happy!