Value vs Reference

Understanding what is a value and a reference in .Net and when to use them.

Value vs Reference in C#.

Update on this page:
03/02/2010: page created.

Value are the simplest types in .Net, they contain their data directly instead of containing a reference to data stored elsewhere in memory. The instances of value type are stored in the stack. Operation like create, read, update and remove are done quicker (and with minimum overhead) by the runtime. All value types are 16 bytes or shorter.
The value types are:

  • Built-in types: (sbyte, byte, short, int, uint, long, float, double, decimal, char, bool, intptr, datetime, …)
  • User-defined types (struct)
  • Enumerations (enum)

Reference types store the address of their data on the stack. Assigning a reference variable to another instance create a second copy of the reference which refers to the same memory location.
Main take away: assigning a value variable to another value variable and changing will create two different data. Assigning a reference variable to another reference variable will create two links to the same data.
To know if an object is of a value or reference type look at the IsValueType property: Object.GetType().IsValueType.

Related content

None yet, please be patient :)