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 string
, class
, 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