A way to print the name of the instance

user2102327 :

I have a class Person:

class Person
{
    public string Name { get; set; }
    public int Age { get; set; }

    public override string ToString()
    {
        return "Person: " + Name + " " + Age;
    }
}

In the Main class, I display the particulars of all the instances of this class (persons):

    List<Person> itemsToPermute = new List<Person>();
    Person a = new Person { Name = "John", Age = 12 };
    Person b = new Person { Name = "Clara", Age = 57 };
    Person c = new Person { Name = "Martha", Age = 81 };
    Person d = new Person { Name = "Leon", Age = 23 };
    Person e = new Person { Name = "Rina", Age = 48 };

    itemsToPermute.Add(a);
    itemsToPermute.Add(b);
    itemsToPermute.Add(c);
    itemsToPermute.Add(d);
    itemsToPermute.Add(e);
    private static void Display(string prompt, List<Person> allPersons)
    {
        foreach (Person currentPerson in allPersons)
        {
            Console.WriteLine(currentPerson.ToString());
        }
    }

The output is: Person: John 12 Person: Clara 57 ... and so on. I would like to be able to also show the instance name: Person: a John 12 Is there a way to retrieve the a (the instance name)? The whole purpose of this question is to learn whether there is a way in C# to programmatically find out the name of the instance of the class. Thank you in advance.

Jon Skeet :

An instance doesn't have a name. A variable has a name, but an object doesn't "know" which variables refer to it, and there could be multiple of them. For example:

Person person1 = new Person { Name = "John", Age = 12 };
Person person2 = person1;

Now both the values of both person1 and person2 refer to the same object - what would you expect the name to be?

Basically, if you want to keep some extra data along with the object, you need to do so explicitly, just like you have done for Name and Age.

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=405803&siteId=1