Sobes.tech
Junior — Middle

Can you give an example of a variable type that references another object in memory?

sobes.tech AI

Answer from AI

In C#, reference type variables store a reference to an object in memory, not the object itself. An example of a reference type is a class.

For example:

class Person
{
    public string Name;
}

Person p1 = new Person();
p1.Name = "Ivan";

Person p2 = p1; // p2 references the same object as p1
p2.Name = "Peter";

Console.WriteLine(p1.Name); // Will output "Peter" because p1 and p2 reference the same object

Here, p1 and p2 are reference type variables; they store the address of the Person object in managed heap.