Sobes.tech
Junior — Middle

How do reference data types work in memory and how do they differ from primitive types?

sobes.tech AI

Answer from AI

In C#, there are two main data types: value types and reference types.

  • Value types store data directly in the memory where they are declared. For example, int, struct. When assigned, the value is copied, and each variable holds its own copy.

  • Reference types store in the variable not the data itself, but a reference (pointer) to the memory location where the data is stored. For example, class, string. When assigned, the reference is copied, not the object, so multiple variables can point to the same object.

Example:

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

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

Thus, reference types allow working with the same object from different variables, while value types store independent copies of data.