3

Duplicate: 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'.
}
Community
  • 1
  • 1

3 Answers3

6

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
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • 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 Apr 05 '10 at 20:13
  • @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 Apr 05 '10 at 20:28
2

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
  • 117,631
  • 17
  • 236
  • 300
0

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
  • 10,331
  • 6
  • 39
  • 55