Understanding Reference Types
Reference type variables are named appropriately (reference) because the variable holds a reference to an object. In C and C++, you have something similar that is called a pointer, which points to an object. While you can modify a pointer, you can't modify the value of a reference - it simply points at the object in memory.
An important fact you need to understand is that when you are assigning one reference type variable to another, only the reference is copied, not the object. The variable holds the reference and that is what is being copied. Listing 22-2 shows how this works.
// Reference Type Assignment
using System;
class Employee
{
private string m_name;
public string Name
{
get { return m_name; }
set { m_name = value; }
}
}
class Program
{
static void Main()
{
Employee joe = new Employee();
joe.Name = "Joe";
Employee bob = new Employee();
bob.Name = "Bob";
Console.WriteLine("Original Employee Values:");
Console.WriteLine("joe = " + joe.Name);
Console.WriteLine("bob = " + bob.Name);
// assign joe reference to bob variable
bob = joe;
Console.WriteLine();
Console.WriteLine("Values After Reference Assignment:");
Console.WriteLine("joe = " + joe.Name);
Console.WriteLine("bob = " + bob.Name);
joe.Name = "Bobbi Jo";
Console.WriteLine();
Console.WriteLine("Values After Changing One Instance:");
Console.WriteLine("joe = " + joe.Name);
Console.WriteLine("bob = " + bob.Name);
Console.ReadKey();
}
}
Here's the output:
Original Employee Values:
joe = Joe
bob = Bob
Values After Reference Assignment:
joe = Joe
bob = Joe
Values After Changing One Instance:
joe = Bobbi Jo
bob = Bobbi Jo