Value vs Reference


Jump to: navigation, search
Exam Prep. Guides
Exam 70-536 Study Guide

1. Types and collections

2. Process, threading,…
3. Embedding features
4. Serialization, I/O
5. .NET Security
6. Interop., reflection,…
7. Global., drawing, text

edit

Contents


An example

This example shows the difference between how a value type works in memory, and how a reference does. First we define a new Value Type and a new Reference Type.

class ReferenceType
{
   public Int32 X;
}
 
struct ValueType
{
   public Int32 X;
}

Now we want to use these types to show how they work:

ReferenceType ref1 = new ReferenceType();
ValueType val1     = new ValueType();
 
ref1.X = 5;
val1.X = 5;

The layout of the memory at this point looks something like the following:

If we now make copies of these values using the following code:

ReferenceType ref2 = ref1;
ValueType val2 = val1;

The layout of the memory now looks something like the following:

If we now change the value of each of the new copies using the following code:

Ref2.X = 8;
Val2.X = 8;

The layout of the memory now looks something like the following:

Summary

  • A variable that is of type value directly contains a value. Assigning a variable of type value to another variable of type value COPIES that value.
  • A variable of type reference, points to a place in memory where the actual object is contained. Assigning a variable of type reference to another variable of type reference copies that reference (it tells the new object where the place in memory is), but does not make a copy of the object.


  • Value types are stored on the stack.
  • Reference types are stored on the heap.


  • Value types can not contain the value null. *
  • Reference types can contain the value null.


  • Value types have a default implied constructor that initializes the default value.
  • Reference types default to a null reference in memory.


  • Value types derive from System.ValueType.
  • Reference types derive from System.Object.


  • Value types cannot derive a new type from an existing value type, but they are able to implement interfaces.
  • Reference types can derive a new type from an existing reference type as well as being able to implement interfaces.


  • Changing the value of one value type does not affect the value of another value type.
  • Changing the value of one reference type MAY change the value of another reference type.


  • The nullable type (only in .NET 2.0) can be assigned the value null.


Previous_Page_.gif Next_Page_.gif

Share this page
  • del.icio.us
  • Facebook
  • Google+
  • StumbleUpon