Junior — Middle
Explain what are data types that store references to objects in memory, and how they differ from value types.
sobes.tech AI
Answer from AI
In C#, data types are divided into value types and reference types.
-
Reference types store in a variable not the data itself, but a reference (pointer) to the memory area where the object data is located. Examples: classes (
class), strings (string), arrays. -
Value types store data directly in the variable. Examples: structures (
struct), enumerations (enum), primitive types (int,bool, etc.).
Differences:
- When assigning, value types copy the data itself, while reference types copy the reference to the object.
- Reference types are placed in managed heap, while value types are usually on the stack or inside other objects.
- Changes in a reference type through one reference are visible through other references to the same object, whereas copies of value types are independent.
Example:
class Person { public string Name; }
struct Point { public int X, Y; }
Person p1 = new Person { Name = "Alice" };
Person p2 = p1; // reference copied
p2.Name = "Bob";
Console.WriteLine(p1.Name); // Outputs "Bob" — both refer to the same object
Point pt1 = new Point { X = 1, Y = 2 };
Point pt2 = pt1; // data copied
pt2.X = 10;
Console.WriteLine(pt1.X); // Outputs 1 — copies are independent