Junior — Middle
Can you name the main data types that use references and explain their features?
sobes.tech AI
Answer from AI
In C#, the main data types that use references are reference types. These include:
- Classes (class) — objects are created on the heap, and the variable stores a reference to the object.
- Interfaces (interface) — the variable holds a reference to an object that implements the interface.
- Arrays (array) — arrays are also reference types.
- Delegates (delegate) — references to methods, also reference types.
Features of reference types:
- The variable stores not the object itself, but a reference to the memory area with the object.
- When assigning, the reference is copied, not the object.
- Objects are created in managed heap, and the garbage collector frees the memory.
- It is possible to have a null value, which means the absence of a reference to an object.
Example:
class Person {
public string Name;
}
Person p1 = new Person { Name = "Ivan" };
Person p2 = p1; // p2 and p1 refer to the same object
p2.Name = "Peter";
Console.WriteLine(p1.Name); // Will output "Peter"