Sobes.tech
Junior — Middle

Kuidas töötavad viidetüübid mälus ja kuidas nad erinevad väärtustüüpidest?

sobes.tech AI

Vastus AI-lt

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 area where the data is located. For example, class, string. When assigned, only 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 = "Иван" };
Person p2 = p1; // copy of the reference
p2.Name = "Пётр";
// p1.Name also "Пётр", because p1 and p2 refer to the same object

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