Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Boxing is the act of casting a value-type instance to a reference-type instance (either an <code>object</code> or an interface), and reference types are allocated on the heap.</p> <p>According to 'C# 4.0 in a Nutshell': " ...unboxing <em>copies</em> the contents of the object back into a value-type instance" and that implies on the stack.</p> <p>In the article you reference, the author states:</p> <pre><code>public static void Main() { Int32 v = 5; // Create an unboxed value type variable Object o = v; // o refers to a boxed version of v v = 123; // Changes the unboxed value to 123 Console.WriteLine(v + ", " + (Int32) o); // Displays "123, 5" } </code></pre> <blockquote> <p>From this code, can you guess how many boxing operations occur? You might be surprised to discover that the answer is three! Let's analyze the code carefully to really understand what's going on. First, an Int32 unboxed value type (v) is created and initialized to 5. Then an Object reference type (o) is created and it wants to point to v. But reference types must always point to objects in the heap, so C# generated the proper IL code to box v and stored the address of the boxed version of v in o. Now 123 is unboxed and the referenced data is copied into the unboxed value type v; this has no effect on the boxed version of v, so the boxed version keeps its value of 5. Note that this example shows how o is unboxed (which returns a pointer to the data in o), <strong>and then the data in o is memory copied to the unboxed value type v.</strong></p> </blockquote>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload