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

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

2 Responses to #219 – Unboxing a Boxed Object

  1. Pingback: #577 – Using the is Operator to Check for an Unboxing Conversion « 2,000 Things You Should Know About C#

  2. Pingback: #1,062 – Unboxing Conversions | 2,000 Things You Should Know About C#

Leave a comment