Saturday, January 12, 2013

C# Nullable Types

As you have seen, CLR data types have a fixed range. For example, the System.Boolean data type can be assigned a value from the set {true, false}. As of .NET 2.0, it is now possible to create nullable data types. Simply put, a nullable type can represent all the values of its underlying type, plus the value null. Thus, if we declare a nullable System.Boolean, it could be assigned a value from the set {true, false,null}. This is significant, as non-nullable value types cannot be assigned the value null:

static void Main(string[] args)
// Compiler errors!
// Value types cannot be set to null!
bool myBool = null;
int myInt = null;

To define a nullable variable type, the question mark symbol (?) is suffixed to the underlying data type. Do note that this syntax is only legal when applied to value types or an array of value types. If you attempt to create a nullable reference type (including strings), you are issued a compile-time error. Like a non-nullable variable, local nullable variables must be assigned an initial value:

static void Main(string[] args)
// Define some local nullable types.
int? nullableInt = 10;
double? nullableDouble = 3.14;
bool? nullableBool = null;
char? nullableChar = 'a';
int?[] arrayOfNullableInts = new int?[10];
// Error! Strings are reference types!
string? s = "oops";

In C#, the ? suffix notation is a shorthand for creating a variable of the generic System.Nullable<T> structure type. Although we will not examine generics until Chapter 10, it is important to understand that the System.Nullable<T> type provides a set of members that all nullable types can make use of. For example, you are able to programmatically discover if the nullable variable indeed has been assigned
a null value using the HasValue property or the != operator. The assigned value of a nullable type may be obtained directly or via the Value property.

No comments:
Write comments
Recommended Posts × +