Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>In .NET, there are two categories of types, <em>reference types</em> and <em>value types</em>.</p> <p>Structs are <em>value types</em> and classes are <em>reference types</em>.</p> <p>The general difference is that a <em>reference type</em> lives on the heap, and a <em>value type</em> lives inline, that is, wherever it is your variable or field is defined.</p> <p>A variable containing a <em>value type</em> contains the entire <em>value type</em> value. For a struct, that means that the variable contains the entire struct, with all its fields.</p> <p>A variable containing a <em>reference type</em> contains a pointer, or a <em>reference</em> to somewhere else in memory where the actual value resides.</p> <p>This has one benefit, to begin with:</p> <ul> <li><em>value types</em> always contains a value</li> <li><em>reference types</em> can contain a <em>null</em>-reference, meaning that they don't refer to anything at all at the moment</li> </ul> <p>Internally, <em>reference type</em>s are implemented as pointers, and knowing that, and knowing how variable assignment works, there are other behavioral patterns:</p> <ul> <li>copying the contents of a <em>value type</em> variable into another variable, copies the entire contents into the new variable, making the two distinct. In other words, after the copy, changes to one won't affect the other</li> <li>copying the contents of a <em>reference type</em> variable into another variable, copies the reference, which means you now have two references to the same <em>somewhere else</em> storage of the actual data. In other words, after the copy, changing the data in one reference will appear to affect the other as well, but only because you're really just looking at the same data both places</li> </ul> <p>When you declare variables or fields, here's how the two types differ:</p> <ul> <li>variable: <em>value type</em> lives on the stack, <em>reference type</em> lives on the stack as a pointer to somewhere in heap memory where the actual memory lives (though note <a href="https://blogs.msdn.microsoft.com/ericlippert/2009/04/27/the-stack-is-an-implementation-detail-part-one/" rel="noreferrer">Eric Lipperts article series: The Stack Is An Implementation Detail</a>.)</li> <li>class/struct-field: <em>value type</em> lives completely inside the type, <em>reference type</em> lives inside the type as a pointer to somewhere in heap memory where the actual memory lives.</li> </ul>
 

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