1

Possible Duplicate:
get name of a variable or parameter

I have this function.

public void AddVariable( String str)
{
    Response.Write(str); // will write the value of str
}

But I need to write the name of the string variable that is passed into the function.

For example:

String temp = "test Variable";
AddVariable(temp);

Here I need to get the name of the variable inside my function, Instead of value.

ie, I need to get 'temp' inside my function, Instead of 'test Variable'.

Is it possbile?

Community
  • 1
  • 1
Akhil Sekharan
  • 12,467
  • 7
  • 40
  • 57

2 Answers2

4

You could get the name of the variable inside the function ("str"), but you cannot get the name of the variable that was passed into the function unless you pass it in as a second parameter.

It doesn't make sense to get the name of the variable passed to the function because there may not have even been a variable if a literal was passed such as AddVariable("test variable").

jam40jeff
  • 2,576
  • 16
  • 14
3

You don't need parameter name (possible from reflection) but rather a variable name that has been passed as a parameter. AFAIK, for all practical purpose, this is not possible for the code within the function.

On the other hand, it's as such possible to do the code analysis of all assemblies loaded in the app-domain and find all invocations to your method and then do the stack-walk to determine possible invocation so that you may able to nail the variable name in the calling method (again if there can be many invocations in calling method, making it difficult to guess the variable name and you have to then rely on IL offset etc) but its just too convoluted.

Perhaps, you can state the reason for such requirements, there can be some alternative. For example, you can get and log stack trace within your method code that can be used for say trouble-shooting.

VinayC
  • 47,395
  • 5
  • 59
  • 72