Value type Vs Reference type in C# from memory point of view?

Value type vs Reference type in C# Interview Question: What is difference between value type and reference type in C#.net from memory point of view?

Answer: Actually, the basic difference between value types and reference types in C#  programming is how they are handled in the memory.

Value Type Vs Reference Type in C#:

  • Value types are stored on stack memory. Whereas C# reference types are stored on heap memory.
  • Value type get freed on its own from stack when they go out of scope. Whereas reference type need garbage collector to free memory.
  • For value types, memory is allocated from stack memory at compile time. Whereas for reference type memory (from heap) is allocated on run time.

Value type in C#:

Value types stored on stack. In below figure, we have declared int a variable and have assigned value 5 that is stored on stack.

When we assign variable a to a new variable say int b i.e. int b=a; value of a will be copied to variable b another space. So, when we modify the value b, value of a will not be changed.

Reference type in C#:

In reference type object will be created on Heap. Consider a class Counter

class Counter { public x;}

Counter c = new Counter()

c.x = 5;

Variable c will be created somewhere in memory that will contain reference (address) of the value x i.e. 5 that is created somewhere else in the memory. See the figure.

If we create another object e.g. Counter c2 = c; c2 will point to the same address of value x.

If we modify c2 object e.g. c2.x =10, the modified value will be reflected for c object also. As there is only one location of value x that are shared by both the object c and c2.

value type vs reference type in csharp

NOTES:

Example of Value type and Reference type in C#

Value type in C#: int, float, char, long, decimal, short, byte, bool, enum and struct etc.

Reference type in C#: class, array, delegate and interface etc.

Related Posts