#581 – Boxing and Unboxing Nullable Types

You can box a value type, converting it to a reference type.

int i = 46;
object o = i;   // Box i

You can also box a nullable type, whether or not the instance of the nullable type currently contains a value.

            int? i1 = null;   // Nullable<int> w/no value
            int? i2 = 42;     // Nullable<int> with a value

            // Boxing nullable types
            object o1 = i1;
            object o2 = i2;

            // Unboxing to nullable types
            int? i3 = (int?)o1;
            int? i4 = (int?)o2;

            bool bHasVal = i3.HasValue;  // false
            bHasVal = i4.HasValue;       // true

When the nullable type is boxed, the underlying value type is stored in the object, rather than an instance of the nullable type itself.  For example, if we box int?, the boxed value will store an int.

About Sean
Software developer in the Twin Cities area, passionate about software development and sailing.

One Response to #581 – Boxing and Unboxing Nullable Types

  1. Pingback: #582 – Use the as Operator to Unbox to a Nullable Type « 2,000 Things You Should Know About C#

Leave a comment