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?
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?
You can't using reflection. GetVariableName is passed the number 3, not a variable. You could do this via code inspect of the IL, but that's probably in the too-hard basket.
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:
static string GetVariableName<T>(Expression<Func<T>> expression)
{
var body = expression.Body as MemberExpression;
return body.Member.Name;
}
static void Main()
{
var someVar = 3;
Console.Write(GetVariableName(() => someVar));
}
Note that this is pretty slow, so don't use it in performance critical paths of your application.