Comprehensive guide to value types, reference types, and their relationships
Value types directly contain their data. Each variable has its own copy of the data, and operations on one variable do not affect another.
Value types are types that store their data directly in the memory location where the variable is allocated. They are stored on the stack unless they are part of a reference type.
Value types are typically allocated on the stack, which makes them faster to access but limited in lifetime to the scope in which they are declared.
When a value type is part of a class (reference type), it is stored on the heap along with the class instance.
Reference types store a reference to the memory location where the data is stored, rather than the data itself.
Reference types store the memory address of the data rather than the data itself. Multiple variables can reference the same data, and operations through one variable affect the data accessed by other references.
Reference types are allocated on the managed heap. The stack contains a reference (memory address) to the actual object on the heap.
The garbage collector automatically manages memory for reference types, freeing objects that are no longer referenced.
C# has a unified type system where all types ultimately inherit from System.Object