tags:

views:

56

answers:

3
foreach(var filter in filters)
{
    var filterType = typeof(Filters);
    var method = filterType.GetMethod(filter);
    if (method != null) value = (string)method.Invoke(null, new[] { value });
}

Is there a case-insensitive way to get a method?

+3  A: 

Yes, use BindingFlags.IgnoreCase:

var method = filterType.GetMethod(filter, BindingFlags.IgnoreCase | BindingFlags.Public | BindingFlags.Instance);

Beware the possible, but unlikely, ambiguity. You'd get an AmbiguousMatchException.

Hans Passant
If there is an ambiguity, what will happen? Will it will just return the first one it finds?
Mark
Mark, if you look at the docs (which I linked to) you'll see it will throw an AmbigousMatchException.
Logan Capaldo
@Logan: Thanks :) This is kind of strange though; if the only change I make to the above code is to add the `BindFlags` arg, my code stops working. `method` becomes null, even with BindingFlags.Default. What would cause it to stop matching *anything*?
Mark
@Mark - my mistake, the default flags no longer apply. Post updated.
Hans Passant
It's actually static, but that fixes it. I'm a bit surprised `BindingFlags.Default` isn't the default binding.
Mark
+1  A: 

Take a look at this variant of GetMethod, specifically note that one of the possible BindingFlags is IgnoreCase.

Logan Capaldo
Ah... `GetMethod` takes quite a few args, I didn't know which one I was supposed to be looking at :) Glossed over that. Thanks!
Mark
A: 

To get a method that acts like GetMethod(filter), except that it ignores the case you need:

var method = filterType.GetMethod(filter, BindingFlags.Public | BindingFlags.Static | BindingFlags.Instance| BindingFlags.IgnoreCase);

This will not work: var method = filterType.GetMethod(filter, BindingFlags.IgnoreCase);

jyoung