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>
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
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.