What is the difference between value types and reference types?

Value types:

  • Stored on the stack.
  • Directly contain their data.
  • Assignments create copies.

Example:

int x = 10;
int y = x; // y gets a copy of x's value
x = 20; // y remains 10

Reference types: 

Store a reference (memory address) to the data on the heap. Examples include stringclass, and arrays. Assigning a reference type copies the reference, not the data itself.

  • Stored on the heap.
  • Contain references (memory addresses) to their data.
  • Assignments copy references.

Example:

class MyClass { public int Value; }
MyClass obj1 = new MyClass { Value = 10 };
MyClass obj2 = obj1; // obj2 references the same object as obj1
obj1.Value = 20; // obj2.Value is also 20

Leave a Reply

Your email address will not be published. Required fields are marked *