Nullable types
Reference types have the default value null
, which indicates that a variable is not assigned to the instance of any object. Value types do not have such an option. However, there are cases when no value is a valid value for a value type too. To represent such cases, you can use a nullable type.
A nullable type is an instance of System.Nullable<T>
, a generic value type that can represent the values of an underlying T
type, which can only be a value type, as well as an additional null
value. The following sample shows a few examples:
Nullable<int> a; Nullable<int> b = null; Nullable<int> c = 42;
You can use the shorthand syntax, T?
, instead of Nullable<T>
; these two are interchangeable. The following examples are alternatives for the preceding ones:
int? a; int? b = null; int? c = 42;
You can use the HasValue
property to check whether a nullable type object has a value, and Value
to access the underlying value:
if (c.HasValue) Console.WriteLine(c.Value);
The following is a list of some of the characteristics of nullable types:
- You assign values to a nullable type object the same way you would assign to the underlying type.
- You can use the
GetValueOrDefault()
method to get either the assigned value or the default value of the underlying type if no value is assigned. - Boxing is performed on the underlying type. If the nullable type object has not assigned any value, the result of boxing is a
null
object. - You can use the null-coalescing operator,
??
, to access the value of the object of a nullable type (for example,int d = c ?? -1;
).
In C# 8, nullable reference types and non-nullable reference types have been introduced. That is a feature that you must opt for in the project properties. It allows you to make sure that only objects of reference types that are declared nullable, using the T?
syntax can be assigned the null
value. Attempts to do so on non-nullable reference types will result in a compiler warning (not an error, because that has the potential to affect large portions of existing code):
string? s1 = null; // OK, nullable type string s2 = null; // error, non-nullable type
You will learn more about nullable reference types in Chapter 15, New Features of C# 8.