Solved

How to get variable name as string

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

DevOps Toolchain Recommendations

Read this Gartner Research Note and discover how your IT organization can automate and optimize DevOps processes using a toolchain architecture.

Question has a verified solution.

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

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…
Exception Handling is in the core of any application that is able to dignify its name. In this article, I'll guide you through the process of writing a DRY (Don't Repeat Yourself) Exception Handling mechanism, using Aspect Oriented Programming.
This tutorial covers a step-by-step guide to install VisualVM launcher in eclipse.
The viewer will learn how to use and create keystrokes in Netbeans IDE 8.0 for Windows.

830 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