What is the difference between value types and reference types in C#?
Stored on the stack (or inline in an object). Assignment copies the value — mutations to one variable don't affect another.
Includes: int, double, bool, char, struct, enum, DateTime
int a = 10;
int b = a; // b is a copy
b = 20;
Console.WriteLine(a); // 10 — unchanged
Stored on the heap; the variable holds a reference (pointer) to the data. Assignment copies the reference — both variables point to the same object.
Includes: class, string, array, interface, delegate
var list1 = new List<int> { 1, 2, 3 };
var list2 = list1; // both point to the same list
list2.Add(4);
Console.WriteLine(list1.Count); // 4 — both see the change
Although string is a reference type, it is immutable. Any operation that appears to modify a string actually creates a new one:
string s1 = "hello";
string s2 = s1;
s2 = s2.ToUpper();
Console.WriteLine(s1); // "hello" — unchanged
int? age = null; // value type made nullable with ?
if (age.HasValue) Console.WriteLine(age.Value);
All Comments