Question

Let's assume I have two method in a class looks like this:

class Foo
{
    public void Convert(string s, int x){ }

    public void Convert(string s, double x) { }
}

If I use:

var method = typeof (Foo)
            .GetMethod("Convert", new[] {typeof (string), typeof (int)});

I'm getting the correct method.But if I change x and make it an out parameter in first method:

public void Convert(string s, out int x) { }

Then I'm getting the second method Convert(string s, double x).

enter image description here

I don't understand why it doesn't return the first method or at least null instead of the second one ? The signature of second method doesn't match with the types I provide. How can I get the correct method in second case ? Is there a way to get it directly ? I know I can get all methods then filter them based on parameter types but I think there should be a direct way of doing this and I am missing it...

Was it helpful?

Solution

Try to use the MakeByRefType method of the Type:

var method = typeof (Foo)
            .GetMethod("Convert", new[] { typeof(string), typeof(int).MakeByRefType() });

OTHER TIPS

I figure out why it doesn't return null, the reason was there is an implicit conversion between double and int and that's why it was matching the second method.

When I change the parameter of second method to a type that can't be convertible to int, for ex. DateTime, I get null, when I try with float I get the same method because int is convertible to float as well.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top