What is the difference between value types and reference types in C#?

What is the difference between value types and reference types in C#?

What is the difference between value types and reference types in C#?

Question

What is the difference between value types and reference types in C#?

Answer

Value Types

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

Reference Types

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

Strings are Special

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

Nullable Value Types

int? age = null; // value type made nullable with ?
if (age.HasValue) Console.WriteLine(age.Value);
All Comments