Nullable types in .NET 2.0
In .NET 1.1 you cannot assign the NULL value to a value type (e.g. int, float, etc.). There are some situations where this is needed, typically in database scenarios. In .NET 2.0 there is a new type called nullable. The nullable type implements the INullableValue interface and looks like:
The idea is that a nullable type combines a value (Value) of the underlying type with a boolean (HasValue) null indicator. The underlying type of a nullable type must be a value type.
Nullable<int> x = 9;
Debug.Assert(x.HasValue);
Debug.Assert(x == 9);
Debug.Assert(x.Value == 9);
Debug.Assert(x.GetValueOrDefault(5) == 9);
x = null;
Debug.Assert(x.HasValue == false);
Debug.Assert(x.GetValueOrDefault(5) == 5);
You can also use the ? type modifier to denote a nullable type.
In .NET 2.0 there is a new operator, called the null coalescing operator
, ??. For example the statement x ?? y
is x
if x
is not null, otherwise the result is y
. Note that this operator also works with reference types.