Sobes.tech
Junior — Middle

What is the difference between reference types and value types in programming?

sobes.tech AI

Answer from AI

In C#, data types are divided into value types and reference types.

Value types store data directly. When assigning or passing to a method, the actual value is copied. Examples: int, double, struct, bool.

Reference types store a reference to the memory location where the data is held. When assigning, the reference is copied, not the data itself, so multiple variables can point to the same object. Examples: class, string, array.

Example:

int a = 5;
int b = a; // copies the value 5
b = 10;
// a is still 5

class Person { public string Name; }
Person p1 = new Person { Name = "Alice" };
Person p2 = p1; // copies the reference
p2.Name = "Bob";
// p1.Name is now "Bob"

Thus, the main difference is in how data is stored and copied: value types copy the values, reference types copy references to objects.