Middle
Explain the difference between reference and value types.
sobes.tech AI
Answer from AI
In C#, types are divided into value types and reference types.
-
Value types store data directly. When assigned or passed to a method, the value is copied. Examples:
int,double,struct,enum. -
Reference types store a reference to an object in memory (heap). When assigned, the reference is copied, not the object itself. Examples:
class,string,array.
Main differences:
- Storage: Value types are usually stored on the stack, reference types on the heap.
- Passing: Value types are passed by value (copy), reference types by reference (reference is copied).
- Mutability: Changes in a copy of a value type do not affect the original; changes through a reference in a reference type are reflected in all references.
Example:
int a = 5;
int b = a; // copy of the value
b = 10;
// a is still 5
class Person { public string Name; }
Person p1 = new Person { Name = "Alice" };
Person p2 = p1; // copy of the reference
p2.Name = "Bob";
// p1.Name is now "Bob"
Understanding the difference is important for memory management and program behavior.