Nullable value types (C# Programming Guide)
Nullable value types are instances of the System.Nullable<T> structure. Nullable value 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.
C# 8.0 introduces the nullable reference types feature. For more information, see Nullable reference types. The nullable value types are available starting with C# 2.
You use a nullable value type when you need to represent the undefined value of an underlying type. A Boolean variable can have only two values:
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 value types have the following characteristics:
Nullable value types represent value-type variables that can be assigned the
T?is shorthand for
Nullable<T>. The two forms are interchangeable.
Assign a value to a nullable value 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 value 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 a variable of an underlying value type based on a nullable-type value:
int? x = null; int y = x ?? -1;. In the example, since
null, the result value of
If a user-defined conversion is defined between two value types, the same conversion can also be used with the corresponding nullable types.
Nested nullable value types are not allowed. The following line doesn't compile: