Nullable types can represent all the values of an underlying type, and an additional null value. Nullable types are declared in one of two ways:
T is the underlying type of the nullable type. T can be any value type including struct; it cannot be a reference type.
For an example of when you might use a nullable type, consider how an ordinary Boolean variable can have two values: true and false. There is no value that signifies "undefined". In many programming applications, most notably database interactions, variables can exist in an undefined state. For example, a field in a database may contain the values true or false, but it may also contain no value at all. Similarly, reference types can be set to null to indicate that they are not initialized.
This disparity can create extra programming work, with additional variables used to store state information, the use of special values, and so on. The nullable type modifier enables C# to create value-type variables that indicate an undefined value.
Each instance of a nullable type has two public read-only properties:
HasValue is of type bool. It is set to true when the variable contains a non-null value.
Value is of the same type as the underlying type. If HasValue is true, Value contains a meaningful value. If HasValue is false, accessing Value will throw a InvalidOperationException.
In this example, the HasValue member is used to test if the variable contains a value before attempting to display it.
Testing for a value can also be done like this: