I wrote the extension method GenericExtension
. Now I want to call the extension method Extension
. But the value of methodInfo
is always null.
public static class MyClass
{
public static void GenericExtension<T>(this Form a, string b) where T : Form
{
// code...
}
public static void Extension(this Form a, string b, Type c)
{
MethodInfo methodInfo = typeof(Form).GetMethod("GenericExtension", new[] { typeof(string) });
MethodInfo methodInfoGeneric = methodInfo.MakeGenericMethod(new[] { c });
methodInfoGeneric.Invoke(a, new object[] { a, b });
}
private static void Main(string[] args)
{
new Form().Extension("", typeof (int));
}
}
Whats wrong?
In case you have an extension method like
you can invoke it (e. g. in tests) like so:
Building off of @Mike Perrenoud's answer, the generic method I needed to invoke was not constrained to the same type as the class of the extension method (i.e.
T
is not of typeForm
).Given the extension method:
I used the following code to execute the method:
where the types defined in
_trackChangesOnTables
are only known at runtime. By using thenameof
operator, this protects against exceptions at runtime if the method or class is ever removed during refactoring.You are passing in string as the generic parameter for your method..
But your constraints say that T needs to inherit from Form (which String does not).
I am assuming you wanted to write
typeof(MyForm)
or some such there instead.The extension method isn't attached to the type
Form
, it's attached to the typeMyClass
, so grab it off that type: