Memory layout for value types
Memory layout for value types

Variables in C# can be classified into two types – reference types and value types. If we know the characteristics of each of them it will be easy for us to use them and optimize the programs we write.

Value types

When a variable is created, memory is allocated in the stack where its value is stored. When we used and assign this variable to another one, the memory in the stack is copied. The two variables have the same value and if they are used after that they work independently. The garbage collector can’t access them, because they are stored in the stack. The enums, structs, predefined types are stored in the stack too and they work in the same way.

Reference types

The reference type is used by reference. That means that the value of the variable (type) is stored in the heap. The stack contains only a pointer (address) to the location in the heap where the actual value is stored. When you want to assign a reference type value to another variable it doesn’t create a copy – only stores the address to the object. If the variable is not used it can be marked for the garbage collector. Reference types are classes, objects, arrays, interfaces, indexes and etc.

Conclusion

Similarities

  • Both are data types.
  • They can have constructors, constants, fields, methods, properties, indexers, operators, events, and nested types.

Differences

  • The class is a reference type.
  • The struct is a value type.
  • Struct slows down the application.
  • Reference type lives in the heap.
  • Value types live in the stack.

Was this post helpful?