Reflection - How to retrieve a member's name?

  • Thread starter Thread starter Udi
  • Start date Start date
U

Udi

Hi,
given a member in a class, I would like to print it's name
automatically (via reflection i guess).

Say I have an ArrayList of objects that contains references to members
of a derived class.
How do I retrieve their names?
Example:

class Base
{
protected ArrayList members;

public string PrintMembersNames()
{
//How to print here the names of my members? i.e "myInt"
}
}

Class Derived : Base
{
int myInt = 0;

public Derived()
{
members.Add( myInt );
}
}


Thanks,
Udi.
 
Thanks Vadim,
But your solution is the other way around,
I'm looking for the NAME of my member according to the member itself,
and not the member itself according to a given name.
Thanks,
Udi.
 
Udi,

The term members generally refers to the fields, methods, and
properties of a class. I think what you want is the name of the
variable that contained the value you added to the ArrayList. The array
list just contains your int value and not the variable name. You can
accomplish this with a different data structure, like a HashTable:

public class Base
{
protected Hashtable members = new Hashtable();

public void PrintMembersNames()
{
//How to print here the names of my members? i.e "myInt"
foreach(string key in members.Keys)
Console.WriteLine(key);
}

}

public class Derived : Base
{
int myInt = 0;

public Derived()
{
members.Add( "myInt", myInt );
}
}

-Carl
 
Udi said:
But your solution is the other way around,
I'm looking for the NAME of my member according to the member itself,
and not the member itself according to a given name.

When you're calling members.Add(myInt) that's exactly equivalent to
writing:

int local = myInt;
members.Add (local);

It's only the *value* which the method can know anything about - not
how that value was arrived at.
 
Back
Top