42

If I have a method such as:

public void MyMethod(int arg1, string arg2)

How would I go about getting the actual names of the arguments? I can't seem to find anything in the MethodInfo which will actually give me the name of the parameter.

I would like to write a method which looks like this:

public static string GetParamName(MethodInfo method, int index)

So if I called this method with:

string name = GetParamName(MyMethod, 0)

it would return "arg1". Is this possible?

svick
  • 236,525
  • 50
  • 385
  • 514
Luke Foust
  • 2,234
  • 5
  • 29
  • 36

4 Answers4

70
public static string GetParamName(System.Reflection.MethodInfo method, int index)
{
    string retVal = string.Empty;

    if (method != null && method.GetParameters().Length > index)
        retVal = method.GetParameters()[index].Name;


    return retVal;
}

The above sample should do what you need.

Tom Anderson
  • 10,807
  • 3
  • 46
  • 63
9

Try something like this:

foreach(ParameterInfo pParameter in pMethod.GetParameters())
{
    //Position of parameter in method
    pParameter.Position;

    //Name of parameter type
    pParameter.ParameterType.Name;

    //Name of parameter
    pParameter.Name;
}
Jeremy
  • 44,950
  • 68
  • 206
  • 332
3

without any kind of error checking:

public static string GetParameterName ( Delegate method , int index )
{
    return method.Method.GetParameters ( ) [ index ].Name ;
}

You could use 'Func<TResult>' and derivatives to make this work for most situations

kͩeͣmͮpͥ ͩ
  • 7,783
  • 26
  • 40
2

nameof(arg1) will return the name of the variable arg1

https://msdn.microsoft.com/en-us/library/dn986596.aspx

Warren Parad
  • 3,910
  • 1
  • 20
  • 29
  • 9
    I'm almost _entirely_ sure that the OP meant from **outside** of the method. All of the other comments, left eight years before yours, also seem to confirm that. – Jay Allen Oct 13 '19 at 12:01