2

I'm trying to use reflection to get a specific MethodInfo of a class, but am unsure how to differentiate between the two following methods:

public class Test
{
    public IBar<T1> Foo<T1>();
    public IBar<T1, T2> Foo<T1, T2>();
}

How can I get a reference to the different Foo methods, assuming I know the number of type parameters? Just calling typeof(Test).GetMethod("Foo") will throw an exception that the method name is ambiguous and there aren't a differing number of parameters to check.

1

1 Answer 1

5

You could get all methods then filter them based on generic argument count:

typeof(Test).GetMethods()
.First(x => x.Name == "Foo" && x.GetGenericArguments().Length == 2);

Note that First method will throw an exception if there is no method that satisfies the condition.You can use FirstOrDefault and check for null instead if you want to avoid exceptions.

Sign up to request clarification or add additional context in comments.

2 Comments

+1. I would be inclined to swap the comparison clauses in the .Where call, though. That way you're only calling GetGenericArguments for methods that have the name you're looking for.
GetGenericArguments was exactly what I couldn't find. Thanks.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.