11.0 Reference & Value Types

Within the .NET Framework, types are either treated as Value Types or Reference Types.

Value Types:

  • Hold their data in its own memory

  • Value type variables are stored in the stack.

Reference Types:

  • Have a pointer that directs to another memory location that actually holds the data

  • Reference type variables are stored in the heap.

Read more about the difference between the heap and the stack here.

Reference

Value Types

As mentioned above, value types store their data on the stack. Value types keep all their data in the same place. When a value type is created, a single space in memory is told to store the value and that variable holds that value. If it is assigned to another variable then the value is copied, both variables work separately, and the value is stored twice. This is similar to what we talked about in the enums module.

string valueType = "This is a value type and is stored on the stack";

Reference Types

Reference types hold a reference that points to where the object is. Reference types represent the address of the variable rather than the actual data. Since they only hold the address, the data cannot be copied. It will just make a copy of the address which will point to the same data. Reference type variables are stored in a different part of the memory called heap. The heap means that once this reference variable is no longer used, it will be brought to the garbage and no longer stored in any memory. Reference types include Classes, Objects, Arrays, Interfaces and more.

A good example of reference types would be someone's business card. The business card is a reference to a person and a little bit about this person, where they can find this person, however it is not that actual person obviously. If you copied your business card, it would not make a copy of you, but it would make a copy of where to find you.

string[] iArray = new string[30];

The space required for the 30 strings is distributed on the heap.

Congratulations on finishing C# Fundamentals!

Last updated