Junior — Middle
Kuidas erinevad viidetüübid väärtusetüüpidest programmeerimises?
sobes.tech AI
Vastus AI-lt
In C#, data types are divided into value types and reference types.
Value types store data directly. When assigned or passed to a method, the value itself is copied. Examples: int, double, struct, bool.
Reference types store a reference to a memory area where the data is located. When assigned, the reference is copied, not the data, 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 still equals 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"
The main difference is in how data is stored and copied: value types copy the values, reference types copy references to objects.