views:

166

answers:

4

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...

+2  A: 

Unfortunately, that's going to be very hard, if not impossible.

Why exactly do you need the name of the variable originally sent in?

Remember that there might not be an actual variable used:

MyMethod2(myVar + "! 123");

In this case, myVar holds just parts of the value, the rest is calculated in the expression at runtime.

Lasse V. Karlsen
thanks - I modified my question to answer yours.
KevinT
+1  A: 

Variables are meant to be convenient identifiers that assign semantic meaning to entities. Programmatically them in the way you're describing seems like a pretty big code smell. Besides, if it's really that important to know, couldn't you just pass in a second parameter?


Edit: The OP updated his question to include this line:

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...

If they explicitly state it and that's important to you, it should definitely be passed in as a parameter to the function.

John Feminella
+2  A: 

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.

Samuel
+1  A: 

It sounds to me like you should be using an Enum as an identifier for your variable, rather than trying to determine the name of your variable. The whole point of a variable is that it's just a human readable name to represent a bit of memory.

You could do:

public void MyTestMethod1()
{
  string myVar = "Hello World";
  MyTestMethod2(myVar, VariableType.MyVar);
}

public void MyMethod2(string parm, VariableType type)
{
  if (type == VariableType.MyVar)
  {
  }
}
Mark Ingram