C# Nullable Types

In this chapter you will learn:

  1. What are C# Nullable Types
  2. Nullable Struct
  3. Example for C# Nullable Types

Description

Reference types can represent a nonexistent value with a null reference. Value types cannot ordinarily represent null values. For example:


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

To represent null in a value type, you must use a special construct called a nullable type. A nullable type is denoted with a value type followed by the ? symbol:


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

Nullable Struct

T? translates into System.Nullable<T>. Nullable<T> is a lightweight immutable structure, having only two fields, to represent Value and HasValue. The essence of System.Nullable<T> is very simple:


public struct Nullable<T> where T : struct
{//from ww  w .ja v  a2 s.  c om
  public T Value {get;}
  public bool HasValue {get;}
  public T GetValueOrDefault();
  public T GetValueOrDefault (T defaultValue);
  ...
}

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() returns Value if HasValue is true; otherwise, it returns new T() or a specified custom default value.

The default value of T? is null.

Example

Implicit and Explicit Nullable Conversions

The conversion from T to T? is implicit, and from T? to T is explicit. For example:


int? x = 5;        // implicit
int y = (int)x;    // explicit

The explicit cast is directly equivalent to calling the nullable object's Value property. Hence, an InvalidOperationException is thrown if HasValue is false.

Next chapter...

What you will learn in the next chapter:

  1. What is C# ToString Method
  2. Example for a simple ToString method
  3. Example for overriding the ToString method
Home »
  C# Tutorial »
    C# Types »
      C# Object
C# Object
C# new operator
C# this Reference
C# Null
C# Nullable Types
C# ToString Method
C# Object Initializers
C# GetHashCode
C# Object Casting and Reference Conversions