Solved

How to get variable name as string

Posted on 2007-11-20
3
2,502 Views
Last Modified: 2013-11-07
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
0
Comment
Question by:gromul
  • 2
3 Comments
 
LVL 7

Expert Comment

by:multithreading
ID: 20321929
foreach(FieldInfo field in myType.GetType().GetFields()) Console.WriteLine(field.Name);
0
 
LVL 55

Assisted Solution

by:Jaime Olivares
Jaime Olivares earned 200 total points
ID: 20321956
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
 
LVL 7

Accepted Solution

by:
multithreading earned 300 total points
ID: 20322019
... 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

Featured Post

3 Use Cases for Connected Systems

Our Dev teams are like yours. They’re continually cranking out code for new features/bugs fixes, testing, deploying, testing some more, responding to production monitoring events and more. It’s complex. So, we thought you’d like to see what’s working for us.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

It was really hard time for me to get the understanding of Delegates in C#. I went through many websites and articles but I found them very clumsy. After going through those sites, I noted down the points in a easy way so here I am sharing that unde…
This article shows how to deploy dynamic backgrounds to computers depending on the aspect ratio of display
The viewer will learn how to use NetBeans IDE 8.0 for Windows to connect to a MySQL database. Open Services Panel: Create a new connection using New Connection Wizard: Create a test database called eetutorial: Create a new test tabel called ee…
The viewer will learn how to use and create keystrokes in Netbeans IDE 8.0 for Windows.

777 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question