What is the most efficient way to ask a MethodInfo how many parameters it takes?
Asked Answered
E

3

14

What is the most efficient way to ask a MethodInfo if it accepts parameters and, if so, how many?

My current solutions would be: methodInfo.GetParameters().Any() and methodInfo.GetParameters().Count().

Is this the most efficient way?

Since I don't actually need any of the ParameterInfo objects, is there a way to do this without a call to GetParameters()?

Endoscope answered 9/2, 2011 at 19:28 Comment(0)
Y
19

The two you listed are for LINQ. Any() returns bool - stating that there is at least one. Count() is used any on IEnumerable<T>.

Length (the property) will be the fastest because GetParameters() returns ParameterInfo[].

It does not appear that MethodInfo have any other way to access the number of parameters other than GetParameters().

Yarkand answered 9/2, 2011 at 19:29 Comment(3)
Are you familiar with MethodImplAttributes or do you know if they could be used to determine this?Endoscope
I am not personally. It does not look like it applies.Yarkand
@smartcaveman: MethodImplAttributes specifies method implementation details. As Daniel correctly assumed, it has nothing to do with the number of method parameters.Flattie
M
5

If efficiency matters why don't you just cache the result in a Dictionary<MethodInfo,int>? That way you only need to use reflection only once.

Marvismarwin answered 9/2, 2011 at 20:10 Comment(0)
T
1

If you want to get the count of parameters of a MethodInfo, then use the below code

int intLength = mi.GetParameters().Length; // where mi is a variable of type MethodInfo
Tynes answered 1/12, 2014 at 6:53 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.