1

How to get MethodInfo for Array.IndexOf<string>(string[], string) ?

I try using this code, but doesn't work.

typeof(Array).GetMethod("IndexOf", 
 BindingFlags.Public | BindingFlags.Static, null, 
  new Type[] { typeof(string[]), typeof(string) }, null);
Coding Junkies
  • 139
  • 2
  • 11
  • 1
    have a look [here](http://stackoverflow.com/questions/269578/get-a-generic-method-without-using-getmethods). – Daniel Hilgarth Feb 03 '12 at 17:11
  • Thanks for your additional information, that give me more understanding of my problem. – Coding Junkies Feb 03 '12 at 17:20
  • 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 06:01

2 Answers2

7

Use BindingFlags.Public | BindingFlags.Static

Edit:

The comment below is correct, the problem is that the IndexOf method is generic - there is only a Array.IndexOf<T>(T[], T). To get that one this is what worked for me:

var indexOfGeneric = typeof(Array).GetMethods(BindingFlags.Public | BindingFlags.Static)
                                  .First(m => m.Name == "IndexOf" 
                                           && m.GetParameters().Length == 2
                                           && m.IsGenericMethod );
BrokenGlass
  • 158,293
  • 28
  • 286
  • 335
4

Found this blog post that seems to achieve what you're asking for;

http://blog.functionalfun.net/2009/10/getting-methodinfo-of-generic-method.html

Sample usage would be as follows;

var m = SymbolExtensions.GetMethodInfo(() => Array.IndexOf<string>(null, null));

This way, you get the MethodInfo of IndexOf<String>(String[], String), instead of IndexOf<T>(T[], T).

Chris McAtackney
  • 5,192
  • 8
  • 45
  • 69