C# Tips

C# Tip Article

When int? value is null

An interesting question: is it possible to access property or method when int? value is null?

Nullable int is expressed in either int? or Nullable<int>. We might have understandable illusion that nullable type is similar to (or equal to) a reference type. Here is code snippet to help you understand what we are talking about.

static void Main(string[] args)
{
    int? i = null;
    if (i == null) // same as (!i.HasValue)
    {                
    }

    // Is it possible to access property when i is null?
    if (i.HasValue)
    {
        //...
    }

    // Is it possible to call method when i is null?
    Console.WriteLine(i.ToString());


    // Boxing
    object o = i;
    // Is it possible to call method when o is null?
    Console.WriteLine(o.ToString());
}

If it were to be a reference type, accessing members from null would be impossible. However, Nullable is a value type, which means it will never get NullReferenceException. Nullable as a value type has physical storage in stack (or heap if it's a part of object members) and any read/write operation can be done with the physical storage.
So for nullable type, it is possible to use property or method even if the value is null.

On a side note, what if we convert nullable type to object (so-called boxing)? If the value of nullable type is null, the result of boxing will pass null. So if any method is called with null object, it will throw NullReferenceException exception.