Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Determining if a parameter uses "params" using reflection in C#?

Consider this method signature:

public static void WriteLine(string input, params object[] myObjects)
{
    // Do stuff.
}

How can I determine that the WriteLine method's "myObjects" pararameter uses the params keyword and can take variable arguments?

like image 542
Gabriel Isenberg Avatar asked Mar 09 '09 19:03

Gabriel Isenberg


3 Answers

Check for the existence of [ParamArrayAttribute] on it.

The parameter with params will always be the last parameter.

like image 129
mmx Avatar answered Oct 18 '22 16:10

mmx


Check the ParameterInfo, if ParamArrayAttribute has been applied to it:

static bool IsParams(ParameterInfo param)
{
    return param.GetCustomAttributes(typeof (ParamArrayAttribute), false).Length > 0;
}
like image 20
Christian C. Salvadó Avatar answered Oct 18 '22 16:10

Christian C. Salvadó


A slightly shorter and more readable way:

static bool IsParams(ParameterInfo param)
{
    return param.IsDefined(typeof(ParamArrayAttribute), false);
}
like image 13
Dejan Avatar answered Oct 18 '22 16:10

Dejan