views:

184

answers:

4

Duplicate: http://stackoverflow.com/questions/742350/determine-the-name-of-the-variable-used-as-a-parameter-to-a-method

Is there any way to retrieve the name of a parameter that was passed into a method e.g.

int someParameter = 1;
Method(someParameter);

public void Method(int parameter)
{
    // I want the name of 'parameter' which will be 'someParameter'.
}
+1  A: 

No, there is no way.

This will be followed by a bunch of people showing weird lambda expression ways to change the call site and kinda get the name, but the short answer is no.

Brian
+4  A: 

No. It's only the value which is passed in as the argument. All the method gets is the integer. The fact that the expression happened to be just evaluating a variable is unknown as far as your method is concerned.

Jon Skeet
Out of interest (I can see no non-WTF reason to actually do this), would changing the parameter to "ref" allow to do this?
Michael Stum
@Michael: Nope. At least, not without some really dodgy unsafe code which was able to test various *possible* variables, and find one which had the same storage location. That *might* be feasible, I'm not sure.
Jon Skeet
+2  A: 

Take a look at this blogpost. It explains it in many ways.

Zaagmans
A: 

The only way perhaps will be with annotations with run-time retention. But then, it will be the name of the annotation, not of the parameter itself. A parameter name is just a syntactic artifact of the language. It does not get carried over to the compiled result.

luis.espinal