class Person
{
string name;
public Person(string name)
{
this.name = name;
}
public void method()
{
Person gupta = new Person("James"); // Current Object
Console.WriteLine(this.name);
Person gupta1 = new Person("Peter"); // Current Object
Console.WriteLine(this.name);
Person gupta2 = new Person("Frank"); // Current Object
Console.WriteLine(this.name);
}
static void Main(string[] args)
{
Person p = new Person("Jim");
p.method();
Console.ReadLine();
}
}
This code produced result
Jim
Jim
Jim
However if thought this should be
James
Peter
Frank
Can somebody explain please?
“Current object” is a rather informal way of speaking. It is ok as long as you don’t get confused about what it refers to.
Do not think of it as a kind of “chronological” measure – the “current object” is not the very object you last instantiated anywere. Instead, it is the instance of the class on which you called the current execution of the method.
At the time of writing “this.(…)”, you don’t know which instance it will be. You will now when the code is called.
Inside this call to
method, “this” will be Lucy – because the methodmethodis being called on that particular instance of Person. The littlePersons you create insidemethodwill not affect this at all.Further clarification: