0

I want to write a function (for example GetVarName) that returns the original name of the variable.

For Example:

public string GetVarName(params object[] vars) { ??? }

public void Main()
{
    int var1 = 5;
    int var2 = var1+11;

    Console.WriteLine(GetVarName(var1));
    Console.WriteLine(GetVarName(var2));
}

Output (needed):

var1 = 5;
var2 = 16;
MethodMan
  • 18,625
  • 6
  • 34
  • 52
Fim Ka
  • 23
  • 3
  • Have you tried anything so far for `GetVarName()`? – lintmouse Oct 31 '15 at 19:47
  • 4
    `Console.WriteLine(nameof(var1));` ? – Bjørn-Roger Kringsjå Oct 31 '15 at 19:50
  • There is the `nameof` operator, or http://stackoverflow.com/a/9801735/340760 – BrunoLM Oct 31 '15 at 19:53
  • Take this implementation: `static string GetVarName(Expression> expr) { var body = (MemberExpression)expr.Body; var getterLambda = Expression.Lambda>(body); var getter = getterLambda.Compile(); return body.Member.Name + " = " + getter(); }` – Gianluigi Liguori Oct 31 '15 at 20:08
  • C# does not recognize nameof function I tried the function of Gianluigi Liguori But how the call statement need to be? Console.WriteLine(GetVarName(var1)); // - It is not working! – Fim Ka Nov 06 '15 at 16:16

0 Answers0