CSharp - Boxing and Unboxing Nullable Values


When T? is boxed, the boxed value on the heap contains T, not T?.

This optimization is possible because a boxed value is a reference type that can already express null.

C# also permits the unboxing of nullable types with the as operator.

The result will be null if the cast fails:


using System;
class MainClass//from w w w  .j a va2  s  .c  o m
   public static void Main(string[] args)
         object o = "string";
         int? x = o as int?;
         Console.WriteLine (x.HasValue);   // False