For example,
static void Main()
{
var someVar = 3;
Console.Write(GetVariableName(someVar));
}
The output of this program should be:
someVar
How can I achieve that using reflection?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
It is not possible to do this with reflection, because variables won’t have a name once compiled to IL. However, you can use expression trees and promote the variable to a closure:
You can use this method as follows:
Note that this is pretty slow, so don’t use it in performance critical paths of your application. Every time this code runs, several objects are created (which causes GC pressure) and under the cover many non-inlinable methods are called and some heavy reflection is used.
For a more complete example, see here.
UPDATE
With C# 6.0, the
nameofkeyword is added to the language, which allows us to do the following:This is obviously much more convenient and has the same cost has defining the string as constant string literal.