Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>In .Net:</p> <p>Often you can't rely on what the type of variable a function will consume, so you need to use an object variable which extends from the lowest common denominator - in .Net this is <code>object</code>.</p> <p>However <code>object</code> is a class and stores its contents as a reference.</p> <pre><code>List&lt;int&gt; notBoxed = new List&lt;int&gt; { 1, 2, 3 }; int i = notBoxed[1]; // this is the actual value List&lt;object&gt; boxed = new List&lt;object&gt; { 1, 2, 3 }; int j = (int) boxed[1]; // this is an object that can be 'unboxed' to an int </code></pre> <p>While both these hold the same information the second list is larger and slower. Each value in the second list is actually a reference to an <code>object</code> that holds the <code>int</code>.</p> <p>This is called boxed because the <code>int</code> is wrapped by the <code>object</code>. When its cast back the <code>int</code> is unboxed - converted back to it's value.</p> <p>For value types (i.e. all <code>structs</code>) this is slow, and potentially uses a lot more space. </p> <p>For reference types (i.e. all <code>classes</code>) this is far less of a problem, as they are stored as a reference anyway.</p> <p>A further problem with a boxed value type is that it's not obvious that you're dealing with the box, rather than the value. When you compare two <code>structs</code> then you're comparing values, but when you compare two <code>classes</code> then (by default) you're comparing the reference - i.e. are these the same instance?</p> <p>This can be confusing when dealing with boxed value types:</p> <pre><code>int a = 7; int b = 7; if(a == b) // Evaluates to true, because a and b have the same value object c = (object) 7; object d = (object) 7; if(c == d) // Evaluates to false, because c and d are different instances </code></pre> <p>It's easy to work around:</p> <pre><code>if(c.Equals(d)) // Evaluates to true because it calls the underlying int's equals if(((int) c) == ((int) d)) // Evaluates to true once the values are cast </code></pre> <p>However it is another thing to be careful of when dealing with boxed values.</p>
 

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