Solved

How to get variable name as string

Posted on 2007-11-20
3
2,501 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

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

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

Introduction Hi all and welcome to my first article on Experts Exchange. A while ago, someone asked me if i could do some tutorials on object oriented programming. I decided to do them on C#. Now you may ask me, why's that? Well, one of the re…
Many of us here at EE write code. Many of us write exceptional code; just as many of us write exception-prone code. As we all should know, exceptions are a mechanism for handling errors which are typically out of our control. From database errors, t…
This tutorial covers a step-by-step guide to install VisualVM launcher in eclipse.
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…

947 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

Need Help in Real-Time?

Connect with top rated Experts

20 Experts available now in Live!

Get 1:1 Help Now