11

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?

abatishchev
  • 98,240
  • 88
  • 296
  • 433
Shaul Behr
  • 36,951
  • 69
  • 249
  • 387
  • possible duplicate of [Select Right Generic Method with Reflection](http://stackoverflow.com/questions/3631547/select-right-generic-method-with-reflection) – nawfal Jan 18 '14 at 05:39

1 Answers1

19

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.

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • 1
    That's nice code just for this method and this class. In general, there must be more and more checks. – Viktor Lova Jul 10 '13 at 12:47
  • You may want to fold the check from the `Where` into `Single`, i.e. `m => m.Name == "Contains" && m.GetParameters().Length == 2` – Sergey Kalinichenko Jul 10 '13 at 12:50
  • @dasblinkenlight: I personally found it more readable in this form. You *could* fold the check in, sure. This is closer to how I think about it though - find all the Contains methods, then find the one which has the right number of parameters. – Jon Skeet Jul 10 '13 at 12:58
  • @nsinreal: Yes, in general it's a pain finding generic methods. – Jon Skeet Jul 10 '13 at 12:59
  • @JonSkeet: hm, I am understanding that there can be nice syntax for generic method choosing. Smth like `GetMethods(types: (Type T) => new Type[] { typeof(IEnumerable<>).WithGenericTypes(T), T })` - through expressions. How do you think, is there real need of such syntax? Can it be writed more better? – Viktor Lova Jul 10 '13 at 13:30
  • @nsinreal: I think it comes up sufficiently rarely for it not to be too bad to just use the kind of code I've given. – Jon Skeet Jul 10 '13 at 13:33