tags:

views:

291

answers:

2

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?

A: 

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.

Marcelo Cantos
+5  A: 

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.

Steven
I am not sure that it's really bad in terms of performance. What might cause performance problems is compiling expression trees, but you don't do it here.
Alexandra Rusina
Look for your self where the `GetVariableName(() => someVar)` gets compiled to using Reflector. Every time this code runs, several objects are created and under the cover many non-inlinable methods are called and some heavy reflection is used. Using expression trees isn't free.
Steven
Yes, you are right. It does have performance cost. But it "relatively" small comparing to compiling expression trees.
Alexandra Rusina
I get your point. You are talking about compiling expression trees at runtime, by calling their `.Compile()` method. I agree that this is even more costlier.
Steven