42

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?

Eran Betzalel
  • 4,105
  • 3
  • 38
  • 66

2 Answers2

75

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>> expr)
{
    var body = (MemberExpression)expr.Body;

    return body.Member.Name;
}

You can use this method as follows:

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. 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 nameof keyword is added to the language, which allows us to do the following:

static void Main()
{
    var someVar = 3;

    Console.Write(nameof(someVar));
}

This is obviously much more convenient and has the same cost has defining the string as constant string literal.

Steven
  • 166,672
  • 24
  • 332
  • 435
  • 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 Apr 02 '10 at 19:06
  • 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 Apr 02 '10 at 20:48
  • Yes, you are right. It does have performance cost. But it "relatively" small comparing to compiling expression trees. – Alexandra Rusina Apr 02 '10 at 23:09
  • 3
    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 Apr 03 '10 at 08:11
  • 5
    +1 for 'even more costlier' :) – Bart Feb 06 '14 at 11:10
  • What if I had var someVar = someOtherVar; and I wanted to get the string "someOtherVar"? Basically, I want to use nameof on the value of the variable. – savram Jun 23 '22 at 04:57
-1

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
  • 181,030
  • 38
  • 327
  • 365