Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get MethodInfo for generic extension method?

I have an IEnumerable<T>, and I want to call the Enumerable.Contains method by reflection. I'm just struggling to get the syntax right. Here's what I currently have:

var containsMethod = typeof(Enumerable).GetMethod("Contains", 
  new[] {
    typeof(IEnumerable<T>), 
    typeof(T) 
  });

This just comes back with a null.

What is the correct way to get the MethodInfo?

like image 389
Shaul Behr Avatar asked Jul 10 '13 12:07

Shaul Behr


1 Answers

What is the correct way to get the MethodInfo?

You have to find the generic method - which is unfortunately a bit of a pain - and then construct that with the appropriate arguments. In this case you know that there are only 2 Contains overloads, and the one you want has two arguments, so you can use:

var method = typeof(Enumerable).GetMethods()
                               .Where(m => m.Name == "Contains")
                               .Single(m => m.GetParameters().Length == 2)
                               .MakeGenericMethod(typeof(T));

You should then be able to invoke it appropriately.

like image 82
Jon Skeet Avatar answered Oct 18 '22 20:10

Jon Skeet