How to get variable name as string

How do I get variable names in a class as strings through reflection? I know that local variables will be renamed but it should be possible for non-locals.

Thanks
gromulAsked:
Who is Participating?
 
multithreadingConnect With a Mentor Commented:
... and if you don't want to use an instance of your class, preferring to reference the class directly, you could write

foreach(FieldInfo field in typeof(MyClass).GetFields()) Console.WriteLine(field.Name);
0
 
multithreadingCommented:
foreach(FieldInfo field in myType.GetType().GetFields()) Console.WriteLine(field.Name);
0
 
Jaime OlivaresConnect With a Mentor Software ArchitectCommented:
Something like this:

For fields:
foreach (System.Reflection.PropertyInfo p in yourClass.GetType().GetFields())
{
      // do something with p.ToString()
}

For properties:
foreach (System.Reflection.PropertyInfo p in yourClass.GetType().GetProperties())
{
      // do something with p.ToString()
}
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.