@Nadeem
You start the program by calling the main method, this creates a NEW Person with the name "Jim" and the variable p points to it.
Person p = new Person("Jim");
You then call
p.method();
So method() is being called from inside p. The method 'method()' makes 3 new Person objects with the names "James", "Peter" and "Frank" but the 'current scope' is still p. You are running 'method()' from inside p.
So if you ask p 'what is your name?', p will say, quite rightly 'Jim'.
When i was studying, I sometimes found it easier to think of it like this - if I have three children and then you ask me what my name is after the birth of each one, my name is still 5arx. You're not asking my children what their name is, you're asking me.
You could revise your code to make things a bit clearer (maybe!):
//Using declarations ommitted for brevity.
public class Person{
public Guid ID;
public string Name;
public Person (string _name){
this.Name = _name;
ID = System.Guid.NewGuid();//creates a unique identifier
}
public void testMethod(){
Console.WriteLine("This code is running inside a Person object: " + this.Identify());
Person g1, g2, g3;
g1 = new Person("Nadeem");
g2 = new Person("Anish");
g3 = new Person("Frank");
this.Identify();// this tells you which class the code is running in - ie. what 'this' means in this context.
//These are the additional objects you created by running testmethod from inside "Jim", the first person you created.
g1.Identify();
g2.Identify();
g3.Identify();
//If you want to get really funky, you can call testMethod() on g1, g2 and g3 too.
//the ID field should help you see what's going on internally.
}
public void Identify(){
Console.WriteLine("Person: ID=" + this.ID + "Name = " + this.Name);//Use string.format in production code!
}
public static void main (string[] args){
Person p = new Person ("Jim");
p.testMethod();
}
}
Hope this helps,
5arx