Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Determine the name of the variable used as a parameter to a method

How would you, in C#, determine the name of the variable that was used in calling a method?

Example:

public void MyTestMethod1()
{
  string myVar = "Hello World";
  MyTestMethod2(myVar);
}

public void MyMethod2(string parm)
{
  // do some reflection magic here that detects that this method was called using a variable called 'myVar'
}

I understand that the parameter might not always be a variable, but the place I am using it is in some validation code where I am hoping that the dev can either explicitly state the friendly name of the value they are validating, and if they don't then it just infers it from the name of the var that they called the method with...

like image 739
KevinT Avatar asked Jan 21 '26 13:01

KevinT


1 Answers

There is a way, but it's pretty ugly.

public void MyTestMethod1()
{
  string myVar = "Hello World";
  MyTestMethod2(() => myVar);
}

public void MyMethod2(Expression<Func<string>> func)
{
  var localVariable = (func.Body as MemberExpression).Member.Name;
  // localVariable == "myVar"
}

As you can see, all your calls would have to be wrapped into lambdas and this method breaks down if you start to do anything else in the lambda besides return a single variable.

like image 104
Samuel Avatar answered Jan 24 '26 07:01

Samuel