Sunday, October 14, 2007

Value Type vs Reference Type

Value Type

  • Instances of value types are stored in an area of memory called the stack (except declared inside a reference type), where the runtime can create, read,update, and remove them quickly with minimal overhead.
  • When you assign between value-type variables, the data is copied from one variable to the other and stored in two different locations on the stack.
  • There are nearly 300 more value types in the Framework.

1. There are three general value types:

  • Built-in types
  • User-defined types
  • Enumerations

2. Built-in types include:

  • All built-in numeric types (int, decimal...)
  • Some non-numeric data types (char, bool, DateTime)

3. User-defined types:

  • User-defined types are also called structures or simply structs.
  • Instances of user-defined typesare stored on the stack and they contain their data directly.
  • Structures behave nearly identical to classes.
  • Example of structs: System.Drawing.Point
  • Structures are usually more efficient than classes.You should define a structure, rather than a class, if the type will perform better as a value type than a reference type.
  • Structure types should meet all of these criteria:
  • ■ Logically represents a single value
  • ■ Has an instance size less than 16 bytes
  • ■ Will not be changed after creation
  • ■ Will not be cast to a reference type

4. Enumerations

  • The purpose of enumerations is to simplify coding and improve code readability by enabling you to use meaningful symbols instead of simple numeric values.

Reference Type

  • Reference types store the address of their data, also known as a pointer, on the stack.The actual data that address refers to is stored in an area of memory called the heap.
  • The runtime manages the memory used by the heap through a process called garbage collection. Garbage collection recovers memory periodically as needed by disposing of items that are no longer referenced.
  • Because reference types represent the address of data rather than the data itself,assigning one reference variable to another doesn't copy the data. Instead, assigninga reference variable to another instance merely creates a second copy of the reference,which refers to the same memory location on the heap as the original variable.
  • There are about 2500 built-in reference types in the .NET Framework. Everything not derived from System.ValueType is a reference type.
  • Example:

StringBuilder first = new StringBuilder();
StringBuilder second = first; //same memory location on the heap.
first.Append ("hello");
first = null; //delete the pointer for 'first', now 'first' doesn't refer to any object. Even though the value of 'first' has changed, the data within the object it used to refer to hasn't changed.
Console.WriteLine (second); //'second' still refers to that object.

Output: hello

blog comments powered by Disqus