#218 – Store Value-Typed Objects on the Heap Through Boxing

Value-typed objects are typically stored on the stack, while reference-typed objects are stored on the heap.  You can, however, convert an instance of a value type to a reference type object through a process known as boxing.

In the example below, we box i, assigning it to a reference type variable.  Because i derives from System.Object (object), as do all types in .NET, we can assign i to o without doing a cast.  A new object is created on the heap, the value of i is copied into it, and the variable o is set to reference the new object.

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

Because a copy of the value-typed object is made, you can change the original object without changing the new object on the heap.

            i = 47;   // i now 47, but o still points to object with value of 46
Advertisements

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

4 Responses to #218 – Store Value-Typed Objects on the Heap Through Boxing

  1. Pingback: #219 – Unboxing a Boxed Object « 2,000 Things You Should Know About C#

  2. Pingback: #581 – Boxing and Unboxing Nullable Types « 2,000 Things You Should Know About C#

  3. Pingback: #1,052 – Boxing Is a Kind of Implicit Conversion | 2,000 Things You Should Know About C#

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

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: