Article Options
Premium Sponsor
Premium Sponsor

 »  Home  »  .NET Framework  »  Copying vs. Cloning  »  Reference Types and Value Types
Copying vs. Cloning
by Phil Eakins | Published  02/09/2006 | .NET Framework | Rating:
Reference Types and Value Types

Value & Reference Types, Summary

As can clearly be seen, the Primitive and Enumerated Types are derived from the ValueType Object (and are, therefore, called Value Types). Everything else derives directly from the Object Type (including, you will note, the String Type) and are described as Reference Types.

The Type of the Object dictates the way in which the Framework allocates memory, as detailed below.


The Value Type

A Value Type is stored as a value on the Thread Stack, ie following:

The Stack will contain the following entries:

Copying Val1 to Val2 (Val2 = Val1) and incrementing Val1 (Val1 += 1) will result in the stack looking like this:

Just as we would expect.


The Reference Type

How do Reference Types differ? Well, quite a lot, Reference Types put their values into the Managed Heap and point to them from the Thread Stack.

Both variables point to the same object.

Adding to the string using Val2 &= "a new word is added" things become very interesting.  As a string is immutable (it cannot be changed) a new Object is entered on the Heap for the concatenated String and its Stack pointer altered:

One side effect of this is that whilst Val1 remains in scope the Garbage Collector cannot reclaim its memory, should the original value not be needed that is. Val1 should be set to Nothing so that collection of the orphan can take place.


Sponsored Links