Nullable Types
A common problem that developers run into with .NET v1.1 is the situation where you want a value type such as an int or bool but you want to allow for the value to also be undefined or null. For example, data coming from a database might not have a value define for one of the fields. The .NET Framework has had special SQL data types to deal with this issue but what if your problem domain isn’t related to SQL?
In .NET 2.0, there is a new generic type
System.Nullable
System.Nullable<bool> myNullableBool = false;
bool? myNullableBool = false;
As ever, C# tries to take the typing out of writing code.
The following code sample shows nullable types in use:
class App {
static void Main() {
int? i = 1;
System.Console.WriteLine("i = {0} ({1})",i,i.HasValue);
i = null;
System.Console.WriteLine("i = {0} ({1})",i,i.HasValue);
}
}
This generates the following output:
i = 1 (True)
i = (False)
Nullable types are only meaningful with value types. string? won’t work because you can already set a string variable to be null.