Junior — Middle
Millised on viite- ja väärtustüübid C#-s ning millised on nende peamised erinevused kasutamisel?
sobes.tech AI
Vastus AI-lt
In C#, types are divided into value types and reference types.
Value types store data directly. Examples: int, double, struct. When assigned or passed to a method, the value itself is copied, creating an independent copy.
Reference types store a reference to an object in memory (heap). Examples: class, string, arrays. When assigned, only the reference is copied, not the object, so multiple variables can refer to the same object.
Main differences:
- Storage: value types are usually on the stack, reference types on the heap.
- Copying: value types are copied by value, reference types by reference.
- Behavior upon modification: changing a value type does not affect other copies, changing an object of reference type reflects in all references.
Example:
int a = 5;
int b = a; // copy of the value
a = 10; // a remains 5
class Person { public string Name; }
Person p1 = new Person { Name = "Иван" };
Person p2 = p1; // copy of the reference
p2.Name = "Пётр"; // p1.Name also changes to "Пётр"