Information Technology Reference
In-Depth Information
Nullable Types
There are situations, particularly when working with databases, where you want to indicate
that a variable does not currently hold a valid value. For reference types, you can do this easily,
by setting the variable to null . When you define a variable of a value type, however, its memory
is allocated, whether or not its contents have any valid meaning.
What you would like in this situation is to have a Boolean indicator associated with the
variable, so that when the value is valid, the indicator is true, and when the value is not valid,
the indicator is false.
Nullable types , new in C# 2.0, allow you to create a value type variable that can be marked
as valid or invalid so that you can make sure a variable is valid before using it. Regular value
types are called non-nullable types .
Creating a Nullable Type
A nullable type is always based on another type, called the underlying type , which has already
been declared.
￿
You can create a nullable type from any value type, including the predefined, simple types.
￿
You cannot create a nullable type from a reference type or another nullable type.
￿
You do not explicitly declare a nullable type in your code. Instead, you declare a variable
of a nullable type . The compiler implicitly creates the nullable type for you, using gener-
ics, as I'll describe later.
To create a variable of a nullable type, simply add a question mark to the end of the name
of the underlying type, in the variable declaration. Unfortunately, this syntax makes it appear
that you have a lot of questions about your code.
Search WWH ::




Custom Search