5
\$\begingroup\$

I am locating the find method of List in C# with the single Expression type parameter

I am using the following ( where T is a List, in my case a SubSonic IActiveRecord )

MethodInfo info = typeof(T).GetMethods(BindingFlags.Static | BindingFlags.Public)
                             .FirstOrDefault(m => m.Name == "Find" && m.GetParameters().Count() == 1);

This works perfectly well, but feels clunky (especially the parameter count part) and I'm not sure how future proof it is.

\$\endgroup\$
6
  • \$\begingroup\$ IEnumerable expose one single method named GetEnumerator... \$\endgroup\$ Mar 10, 2011 at 22:06
  • \$\begingroup\$ @VirtualBlackFox It also exposes many extension methods in C#3+ for use with LINQ \$\endgroup\$
    – johnc
    Mar 10, 2011 at 22:23
  • \$\begingroup\$ 1.GetMethod on IEnumerable<T> will never return theses. 2.None is called "Find" in the framework. 3.Look like you are searching on a List<T> as this one define a one parameter "Find" taking a predicate. \$\endgroup\$ Mar 10, 2011 at 22:28
  • \$\begingroup\$ @VirtualBlackFox Oh, you are correct. I always assumed it was an IEnumerable extension method, thanks. Question edited accordingly \$\endgroup\$
    – johnc
    Mar 10, 2011 at 22:37
  • 2
    \$\begingroup\$ Is there a reason you're not just using GetMethod? \$\endgroup\$
    – sepp2k
    Mar 10, 2011 at 23:24

1 Answer 1

6
\$\begingroup\$

When searching for methods using reflection I found that the most future-proof way is by searching exactly for the method, so not only the Count() is correct but I would also have checked both what is this parameter type and what is the return type of the function.

\$\endgroup\$
2
  • \$\begingroup\$ Thanks, less elegant, but more constrained and future proof, makes sense \$\endgroup\$
    – johnc
    Mar 10, 2011 at 23:03
  • \$\begingroup\$ Yes the case where you need to find a function with a Something<OtherThing<T>> paramter where T is a generic parameter of the parent class produce especially non elegant code. If someone took the time I guess that designing a small DSL for this could be possible. \$\endgroup\$ Mar 10, 2011 at 23:13

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.