Difference Between Value Type & Reference Type in C#

Difference Between Value Type & Reference Type in C#
Difference Between Value Type & Reference Type in C#

We already know that int, double, float, struct etc are value type and classes, interface, delegates etc are reference type.  Now, this is the time to elaborate them a bit more, so that you can understand what actual happens behind the scenes.

Value Type:  Value types are always stored in the stack.  They hold their value where they are declared in memory.  Value types get destroyed when their scope ends.  Whenever you copy one value type into another, a new copy gets created.  Any modification made to second value type would not affect the first value type and vice versa.

Reference Type:  Reference types are always stored on the heap.  The reference variable is stored on the stack, but the object to which it points to, is created on the heap.  Like value types, reference variables also get destroyed when their scope ends.  The object on the heap later destroyed by the garbage collector.  Garbage collector basically checks if any reference variable is pointing to it or not.  If not, then it gets destroyed.  Whenever you copy one reference type into another, they both points to the same object on the heap.  Thus, any changes to made to any of the reference type would affect both of them.

Figure is given below to demonstrate how value type and reference type behave when you copy them into another similar type.

valref