How is "this" passed in C#
You've changed the Person
instance that firstPerson.instance
is pointing to, but not the original instance that firstPerson
refers to.
So firstPerson
is still pointing to the original Person
instance (and so firstPerson.name
returns the value set in the first instance), while firstPerson.instance
is now pointing to a new (second) Person
instance.
Person firstPerson = new Person(); // instance 1
Person secondPerson = firstPerson.myself; // myself refers to instance 1
secondPerson.name = "Bill"; // set name in instance 1
Console.WriteLine(firstPerson.name); // get name from instance 1
Console.WriteLine(secondPerson.name); // get name from myself in instance 1
Console.WriteLine(firstPerson.myself.name); // get name from instance 1 (same as above)
firstPerson.myself = new Person(); // myself refers to instance 2, but firstPerson still refers to instance 1
Console.WriteLine(firstPerson.name); // still getting name from instance 1
Console.WriteLine(secondPerson.name); // still getting name from myself in instance 1
Console.WriteLine(firstPerson.myself.name); // get name from instance 2 (since firstPerson.myself was reassigned)
firstPerson = new Person(); // firstPerson and firstPerson.myself point to instance 3
Console.WriteLine(firstPerson.name); // get name from instance 3, which is the default "Eddie"
Console.WriteLine(secondPerson.name); // still points to instance 1, since that's what it was when it was assigned
Console.WriteLine(firstPerson.myself.name); // get name from instance 3 (since firstPerson.myself is defaults to the new instance again)
this
represent current instance of of a class.
When you are creating new instance of Person firstPerson.mySelf
, that time it will refer to the new instance of Person
class.
Person firstPerson = new Person();
Person secondPerson = firstPerson.myself; //Here you are referencing to same instance of Person class i.e. same `this`
But when you are creating new instance of Person
, it will refer to new this
firstPerson.myself = new Person(); // New instance new `this`, but still `firstPerson` is referencing to previous instance
Explanation with diagram
In your case you created new instance of person and stored in
myself
property. butfirstPerson
andsecondPerson
is still pointing to samethis
instance
The myself
is just a variable. So when you call
Person firstPerson = new Person();
you have 2 variables which point to the same instance: firstPerson
and firstPerson.myself
. With line
Person secondPerson = firstPerson.myself;
you introduce third variable which still points to the same instance. Now with
firstPerson.myself = new Person();
you create second instance and make firstPerson.myself
point to this instance while the variables firstPerson
and secondPerson
still point to the first one.