I know I could use a technique like in this question to get my method.
E.g
MethodInfo firstMethod = typeof(Enumerable)
.GetMethods(BindingFlags.Public | BindingFlags.Static)
.First(m => m.Name == "FirstOrDefault" && m.GetParameters().Length == 1)
I want to shortcut that process though.
I'm looking for Enumerable.FirstOrDefault Method (IEnumerable)
I've tried both
// I'm just using string just as an example.
var enumerableType = typeof(IEnumerable<>).MakeGenericType(typeof(string));
MethodInfo firstMethod = typeof(Enumerable)
.GetMethod("FirstOrDefault", new Type[] { enumerableType });
and
MethodInfo firstMethod = typeof(Enumerable)
.GetMethod("FirstOrDefault", Type.EmptyTypes);
But both return null
.
What would be the correct approach?
Unfortunutely there is no easy way to get the correct overload when the parameter type is generic. You can do it using
LINQ
manually:In this case since the
FirstOrDefault
has only one overload that takes one parameter you can remove the last condition.But it is necessary when there are overloads that takes same number of parameters of different types.