A reference type variable has two parts: the object and its address.
A reference type variable stores the address of the object, not the object itself.
The following code creates a Rectangle class, which is a reference type.
using System;
class Rectangle
{
public int Width = 5;
public int Height = 5;
}
class Program
{
static void Main(string[] args)
{
Rectangle r1 = new Rectangle();
Rectangle r2 = r1;
Console.WriteLine("r1.Width:" + r1.Width);
Console.WriteLine("r2.Width:" + r2.Width);
r1.Width = 10;
Console.WriteLine("r1.Width:" + r1.Width);
Console.WriteLine("r2.Width:" + r2.Width);
}
}
The output:
r1.Width:5
r2.Width:5
r1.Width:10
r2.Width:10
In the main method two variable r1 and r2 are created. They both point to the same object.
We can see that as we change the width through r1 the r2.Width gets the change as well.
+----+ +------------------+ +----+
| r1 | --->| rectangle object | <--- | r2 |
+----+ +------------------+ +----+