#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

About Sean
Software developer in the Twin Cities area, passionate about .NET technologies. Equally passionate about my own personal projects related to family history and preservation of family stories and photos.

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

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 )

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

Follow

Get every new post delivered to your Inbox.

Join 43 other followers