How to get the name of a variable

A

ad

How to get the name of a variable, not the value!
For example, I declare an int variable:

int iMyVariable=5;

How to get the name "iMyVariable" of iMyVariable" ?
 
B

Bruce Wood

You mean as a string that you could, for example, print out?

The short answer is that you can't, and the brief reason is that
there's no guarantee that that variable even exists at run time. It's
common that the compiler optimize away variables, so that the running
code doesn't much resemble what you wrote (although it does _do_
exactly the same thing as what you wrote).

The longer answer is that if you compile in debug mode, the compiler
generates pdb files along with your dlls and executables. Somewhere in
there are stored the names of your variables and other information
about them. How to get at that, I have no idea.

However, if all you have is a dll or an exe, then so far as I know
you're out of luck.

Now, if your

int iMyVariable = 5;

is a field in one of your classes, then that's a different story. You
can get at fields, properties, and methods using "Reflection". See the
System.Reflection namespace for details.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top