Understanding the difference between Value Types and Reference Types is one of the most important fundamentals in C#. It directly impacts memory usage, performance, method behavior, and bug prevention.
In this article, we will explore what value types and reference types are, how they behave in memory, how assignment and method calls differ between them, and when to use each one in real applications.
What is Value Type in C#?
Value types store actual data directly. When a value type variable is assigned to another variable, a copy of the data is created. Each variable maintains its own independent copy.
Common value types include:
- int
- float, double, decimal
- bool
- struct
- enum
int a = 10; int b = a; b = 20; Console.WriteLine(a); // 10 Console.WriteLine(b); // 20
What is Reference Type in C#?
- class
- string
- array
- object
- interface
- delegate
class Person { public int Age; } Person p1 = new Person { Age = 25 }; Person p2 = p1; p2.Age = 30; Console.WriteLine(p1.Age); // 30
Pass By Value Vs Pass By Reference.
void ChangeValue(int number) { number = 50; } int x = 10; ChangeValue(x); Console.WriteLine(x); // Output: 10
void ChangeValue(ref int number) { number = 50; } int x = 10; ChangeValue(ref x); Console.WriteLine(x); // Output: 50
void GetValues(out int result) { result = 100; } int x; GetValues(out x); Console.WriteLine(x); // Output: 100
How Memory Allocation Works in C#?
In C#, memory is mainly managed using two logical areas: the stack and the heap. Understanding how they work helps explain performance, object lifetime, and behavior of value and reference types.
Stack Memory
The stack stores value types and method call information. Memory allocation on the stack is very fast and is automatically cleaned up when a method finishes execution.
Key points:
- Stores local value-type variables
- Follows Last-In-First-Out (LIFO)
- Memory is freed automatically when the scope ends
void Test() { int x = 10; // stored on stack }
Heap Memory
- Stores objects created using new
- Accessed via references
- Cleaned by GC, not immediately
class Person { public int Age; } void Test() { Person p = new Person(); // object on heap, reference on stack }
Why is string Immutable but still a Reference Type in C#?
Note: An immutable object is one whose state cannot be changed after creation. Any modification creates a new object instead of changing the existing one.
- Strings can be large and variable in size
- Storing them on the heap avoids costly copying
- Multiple variables can reference the same string instance
string s1 = "Hello"; string s2 = s1;
string s1 = "Hello"; string s2 = s1; s2 = "World"; Console.WriteLine(s1); // Hello Console.WriteLine(s2); // World
String is a reference type for performance reasons, but immutable to ensure security, thread safety, and safe sharing through interning.
No comments
Post a Comment