CSharp - Nullable Nullable Types


Reference types, such as interface and class, can use null to represent non-exist value.

Value types cannot be assigned null values.

For example:

string s = null;       // OK, Reference Type
int i = null;          // Compile Error, Value Type cannot be null

To use null in a value type, use a nullable type.

A nullable type is a value type followed by the ? symbol:

int? i = null;                     // OK, Nullable Type
Console.WriteLine (i == null);     // True

Nullable<T> Struct

ValueType? is converted to System.Nullable<T>.

System.Nullable<T> is a immutable structure with two fields: Value and HasValue.

The code:

int? i = null;
Console.WriteLine (i == null);              // True

translates to:

Nullable<int> i = new Nullable<int>();
Console.WriteLine (! i.HasValue);           // True

Attempting to retrieve Value when HasValue is false throws an InvalidOperationException.

GetValueOrDefault() from System.Nullable<T> returns Value if HasValue is true; otherwise, it returns new T() or a specified custom default value.

The default value of T? is null.