views:

228

answers:

2

Hi,

I'm trying to get a class memeber variable list at run time. I know this probably using typeof and reflections. but can't find an example. Please someone shed light for me.

Here is pseudo code example:

Class Test01
{ 
 public string str01;
 public string str02;
 public int myint01;
}

I want something like this (pseudo code):

Test01 tt = new Test01();
foreach(variable v in tt.PublicVariableList)
{
   debug.print v.name;
   debug.print v.type;
}

Please help me figure out how to do this in C# VS2005

Thanks a lot

+7  A: 

If you're after public fields just use tt.GetType().GetFields()

If you need other members, use GetProperties(), GetMethods(), GetEvents() etc for specific ones, or GetMembers() to get them all.

Each method has an overload accepting a BindingFlags if you want to access non-public members, or restrict the search to static members (or just to instance members).

Jon Skeet
Thanks a lot. This is awesome.
simon
+1  A: 
foreach (MemberInfo mi in tt.GetType().GetMembers()) ...
leppie
You guys are incredible. Thank you.
simon