469,076 Members | 1,503 Online
Bytes | Developer Community
New Post

Home Posts Topics Members FAQ

Post your question to a community of 469,076 developers. It's quick & easy.

Reflection - How to retrieve a member's name?

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.

Mar 22 '06 #1
3 1206
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.

Mar 22 '06 #2
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

Mar 22 '06 #3
Udi <Ud**********@gmail.com> wrote:
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.

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet Blog: http://www.msmvps.com/jon.skeet
If replying to the group, please do not mail me too
Mar 22 '06 #4

This discussion thread is closed

Replies have been disabled for this discussion.

Similar topics

7 posts views Thread by John | last post: by
8 posts views Thread by Robert W. | last post: by
1 post views Thread by Tony Johansson | last post: by
7 posts views Thread by =?Utf-8?B?UVNJRGV2ZWxvcGVy?= | last post: by
6 posts views Thread by Cralis | last post: by
1 post views Thread by CARIGAR | last post: by
reply views Thread by zhoujie | last post: by
By using this site, you agree to our Privacy Policy and Terms of Use.