C# Interview Question #5

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

C# & .NET Fundamentals Junior Beginner

Quick Interview Answer

Value types contain their data directly, while reference types hold a reference to an object.

Detailed Explanation

Value types contain their data directly, while reference types hold a reference to an object.

Common value types include int, double, float, decimal, bool, char, struct, and enum. Common reference types include class, string, array, interface, delegate, and object.

When one value-type variable is assigned to another, its value is copied. With reference types, assigning one variable to another normally copies the reference, so both variables can refer to the same object.

Code Example

int a = 10;
int b = a;
b = 20;
// a is still 10

Person p1 = new Person { Name = "Ali" };
Person p2 = p1;
p2.Name = "Ahmed";
// p1.Name is now "Ahmed" because both refer to the same object.