Reflection and the params Keyword
- by Robert May
I’ve had to look this up a couple of times, and there’s not much out there, so I end up guessing the same answer over and over. When using MethodBase.GetParameters() to get an array of ParameterInfo object, I often want to get a count of the number of parameters that are out, optional, params, etc. For out and optional, you can simply check ParameterInfo.IsOut or ParameterInfo.IsOptional or any number of other “Attributes”. However, for params, there isn’t a property on ParameterInfo. Instead, you have to do this: info.GetCustomAttributes(typeof(ParamArrayAttribute), true)
This will get you a set of all of the attributes that are the ParamArrayAttribute, which you can then turn into a linq statement that looks like this:
methodParameters.Count(info => info.GetCustomAttributes(typeof(ParamArrayAttribute), true).Count() > 0);
Which, assuming that methodParameters is the result of MethodBase.GetParameters, will give you a count of the number of parameters that have the params keyword. Of course, there can be only one, but who’s counting!
Now, hopefully, the next time I try to look this up, my own blog will get the values.
Technorati Tags: Reflection