I have a doubt on how reference types actually work. I have a class Person with two properties Name and Age. I am creating an object of Person class (objPerson1), assigning some values to both the properties and assigning that object to another of type Person (objPerson2). Now the question is after assigning when I change the Name and Age property and print them both the object shares same Name and Age which is fine as they are reference type.But when I assign null value to object itself then other object doesn't get nullified.Below is the code
class Person
{
public string Name { get; set; }
public int Age { get; set; }
}
public static void Main(string[] args)
{
Person objPerson1 = new Person();
objPerson1.Name = "Tom";
objPerson1.Age = 10;
Person objPerson2 = objPerson1;
objPerson2.Name = "Jerry";
objPerson2.Age = 15;
Console.WriteLine($" Person1-{objPerson1.Name},{objPerson1.Age} and Person2-{objPerson2.Name},{objPerson2.Age}");
//Above line prints Person1-Jerry,15 and Person2-Jerry,15
//which is right as both are sharing same address.But when I wrote following code it confused me alot.
}
public static void Main(string[] args)
{
Person objPerson1 = new Person();
objPerson1.Name = "Tom";
objPerson1.Age = 10;
Person objPerson2 = objPerson1;
objPerson2 = null;
//After executing above line objPerson2 was null but objPerson1 were still having the values for Name and Age.
}
As they are reference type and both pointing to same address if I assign null to objPerson2 ,objPerson1 should also be null and vice-versa.Correct me if I'm wrong
A bit simplified, but hopefully sufficient for you to understand:
Person objPerson1 = new Person();
Heap: memory allocated for object
Stack: objPerson1
= address of the heap object
objPerson1.Name = "Tom";
objPerson1.Age = 10;
Heap: is being filled with values.
Stack: unchanged (still the same address)
Person objPerson2 = objPerson1;
Stack: another variable gets the same address
Heap: unchanged
objPerson2 = null;
Stack: the variable objPerson2
gets the value 0x00000000
.
Note that objPerson1
still has the address of the heap and the object on the heap still exists. So objPerson1
still "works".