Nullable types (C# Programming Guide)
Nullable types are instances of the System.Nullable<T> struct. Nullable types can represent all the values of an underlying type
T, and an additional null value. The underlying type
T can be any non-nullable value type.
T cannot be a reference type.
You use a nullable type when you need to represent the undefined value of an underlying type. A Boolean variable can have only two values: true and false. There is no "undefined" value. In many programming applications, most notably database interactions, a variable value can be undefined or missing. For example, a field in a database may contain the values true or false, or it may contain no value at all. You use a
Nullable<bool> type in that case.
Nullable types have the following characteristics:
Nullable types represent value-type variables that can be assigned the
nullvalue. You cannot create a nullable type based on a reference type. (Reference types already support the
T?is shorthand for
Nullable<T>. The two forms are interchangeable.
Assign a value to a nullable type just as you would for an underlying value type:
int? x = 10;or
double? d = 4.108;. You also can assign the
int? x = null;.
You can also use the
!=operators with a nullable type, as shown in the following example:
if (x != null) y = x.Value;. If
bare both null,
a == bevaluates to
Beginning with C# 7.0, you can use pattern matching to both examine and get a value of a nullable type:
if (x is int valueOfX) y = valueOfX;.
The default value of
T?is an instance whose HasValue property returns
Use the GetValueOrDefault(T) method to return either the assigned value, or the provided default value if the value of the nullable type is
Use the null-coalescing operator,
??, to assign a value to an underlying type based on a value of the nullable type:
int? x = null; int y = x ?? -1;. In the example, since
xis null, the result value of
If a user-defined conversion is defined between two data types, the same conversion can also be used with the nullable versions of these data types.
Nested nullable types are not allowed. The following line doesn't compile: