How to call a generic extension method with reflection?
The extension method isn't attached to the type Form
, it's attached to the type MyClass
, so grab it off that type:
MethodInfo methodInfo = typeof(MyClass).GetMethod("GenericExtension",
new[] { typeof(Form), typeof(string) });
In case you have an extension method like
public static class StringExtensions
{
public static bool IsValidType<T>(this string value);
}
you can invoke it (e. g. in tests) like so:
public class StringExtensionTests
{
[Theory]
[InlineData("Text", typeof(string), true)]
[InlineData("", typeof(string), true)]
[InlineData("Text", typeof(int), false)]
[InlineData("128", typeof(int), true)]
[InlineData("0", typeof(int), true)]
public void ShouldCheckIsValidType(string value, Type type, bool expectedResult)
{
var methodInfo =
typeof(StringExtensions).GetMethod(nameof(StringExtensions.IsValidType),
new[] { typeof(string) });
var genericMethod = methodInfo.MakeGenericMethod(type);
var result = genericMethod.Invoke(null, new[] { value });
result.Should().Be(expectedResult);
}
}