Sobes.tech
Junior — Middle

Explain the differences between data types that store references and those that store values.

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 value itself is copied. Examples: int, double, struct, bool.
  • Reference types store a reference to the memory area where the data is located. When assigning, the reference is copied, not the data itself. Examples: class, string, arrays.

Example:

int a = 5;
int b = a; // b gets a copy of the value 5
b = 10;
// a is still 5

class Person { public string Name; }
Person p1 = new Person { Name = "Ivan" };
Person p2 = p1; // p2 and p1 refer to the same object
p2.Name = "Peter";
// p1.Name is also "Peter"

Thus, changes in reference types affect all references pointing to the same object, while value types are independent after copying.