The C# 2.0 specification will bring a lot of changes to the language. One of those changes will be the addition of nullable value types via the “?” type. In addition to the nullable type and the “?” syntax is the “??” operator. I read about this a while back and was just reminded of it, and the fact that it is now out in the open, when I read it again on Armand du Plessis' blog.
A nullable value type is declared as follows:
//declare a nullable int variable
int? x = null;
This is telling the compiler/runtime that this int is a value type can hold the value null. You can test for null just the same way you would with a reference type.
if (x == null)
Easy enough, but it does take some planning and fore-thought as to whether you want to allow for your value type variables to be assigned a null value (since you need to account for that in the declaration). From there you can test for null just as if it were a reference type. Or you can use the new “??” operator.
The new ?? binary operator allows you to conditionally test for null and use an alternative value instead. For example, consider the following assignment.
int myvalue = (x != null ? x : 0);
With the ?? operator, this can be rewritten as:
int myvalue = x ?? 0;
This indicates to assign the value of x to the myvalue variable or 0 in the case that x is null.
According to Ted Neward, nothing has really changed for value types with this addition:
Under the hood, nothing has changed, believe it or not; this was introduced as part of the support for generics, via the System.Nullable<X> type. Nullable<> is a generic wrapper around any value type, and introduces a boolean property "HasValue", to indicate whether the wrapper actually has a value in it, or is in fact pointing to null. The conversion between int? and Nullable<int> is purely a linguistic one, much in the same way the "conversion" between int and System.Int32 is.
There is some controversy around these new nullable types. The biggest part of the debate exists around the “lifting” of types, where a nullable value type is coerced into a value. For example, to compare a null int with a regular int and the null int will be lifted, or promoted, to an integer value - such as 0. This is why you must use the ?? operator for comparisons or other operations to avoid having the value lifted.
I'm sure they'll get it right before 2.0 comes out. As far as I know, the exact syntax and usage for nullable value types and the ?? operator is still a bit up in the air. But I think I like the it and am excited about the change. I'll have to think of some good reasons to use it and test out the waters a bit.