Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get names of the params passed to a C# method

Tags:

c#

void MyMethod(string something, params object[] parameters)
    {
      foreach (object parameter in parameters)
      {
        // Get the name of each passed parameter
      }
    }

For example, if I call the method in the following way, I want to get the names "myFirstParam" and "anotherParam".

string myFirstParam = "some kind of text";
string anotherParam = 42;
MyMethod("test", myFirstParam, anotherParam);

Perhaps reflection is the answer? Perhaps it's just not possible? I am aware of the existance of this question, but that solution won't work here.

(Please do not respond with "This is not a good idea". That is not my question.)

like image 372
Niels Brinch Avatar asked May 17 '11 03:05

Niels Brinch


Video Answer


1 Answers

This is totally impossible.

Here are just a few cases where it doesn't even make sense:

MyMethod("abc", new object[5]);
MyMethod("abc", "def");
MyMethod("abc", var1 + var2);
MyMethod("abc", SomeMethod());
MyMethod("abc", b ? a : c);
MyMethod("abc", new object()); 
MyMethod("abc", null);

In fact, local variable names aren't even compiled into the assembly.

like image 171
SLaks Avatar answered Sep 23 '22 07:09

SLaks