#219 – Unboxing a Boxed Object

If you’ve converted a value-typed object to a reference-typed object by boxing it, you can later unbox the object, converting it back to a value type.

Assume that we’ve boxed an integer value as follows:

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

Now we have a copy of the integer in a new object on the heap.

We can later convert this object back to a value type.  This is known as unboxing.

            int j = (int)o;  // Unbox

When we unbox, we need to explicitly cast the object to the value type.  Because the integer derives from System.Object, we can convert it to an object implicitly, but when converting from an object to an int, we need an explicit cast.

As with boxing, unboxing copies the value of the heap-based object.  It does not delete the object on the heap or free its memory.