Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unexpected behavior using Type.GetMethod(string name, Type[] types)

Tags:

c#

.net

Consider the following code:

public static class FooHelpers
{
    public static void Foo(int bar)
    {
        //...
    }
    public static void Foo(uint bar)
    {
        //...
    }
    public static void Foo(long bar)
    {
        //...
    }
    public static void Foo(ulong bar)
    {
        //...
    }
}

Now I have some reflection code that is given a type and checks to see if there exists a Foo method with a parameter of the given type. If there does not exist such a Foo method, my program needs to skip a step. Here is a method to accomplish this:

public static MethodInfo GetFooMethodIfExists(Type parameterType)
{
    return typeof(FooHelpers).GetMethod("Foo", new Type[] { parameterType });
}

Seems like a reasonable solution, no? According to the documentation on Type.GetMethod(string name, Type[] types):

// Returns:
//     A System.Reflection.MethodInfo object representing the public method whose
//     parameters match the specified argument types, if found; otherwise, null.

Now, let's try the following:

MethodInfo m = GetFooMethodIfExists(typeof(short));

Instead of returning null, it returned the method with the int parameter. I just finished a reflection-heavy project that relied on the output of Type.GetMethod(string name, Type[] types) to behave as the documentation states, and it's causing a lot of issues.

Can anyone please tell me why this is happening and/or explain a different way of doing this?

like image 368
Mr Anderson Avatar asked Jun 17 '26 11:06

Mr Anderson


1 Answers

BindingFlags.ExactBinding will fix your problem. Basically, it forces reflection to be strict regarding parameter types. Here is how you can fix your method to use this flag:

public static MethodInfo GetFooMethodIfExists(Type parameterType)
{
    return typeof (FooHelpers).GetMethod(
        "Foo",
        BindingFlags.Static | BindingFlags.Public | BindingFlags.ExactBinding,
        (Binder) null,
        new[] {parameterType},
        (ParameterModifier[]) null);
}
like image 54
Yacoub Massad Avatar answered Jun 19 '26 01:06

Yacoub Massad



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!