Inspired by Enigmativity's answer - let's assume you have two (or more) classes, like
public class Bar { }
public class Square { }
and you want to call the method Foo<T>
with Bar
and Square
, which is declared as
public class myClass
{
public void Foo<T>(T item)
{
Console.WriteLine(typeof(T).Name);
}
}
Then you can implement an Extension method like:
public static class Extension
{
public static void InvokeFoo<T>(this T t)
{
var fooMethod = typeof(myClass).GetMethod("Foo");
var tType = typeof(T);
var fooTMethod = fooMethod.MakeGenericMethod(new[] { tType });
fooTMethod.Invoke(new myClass(), new object[] { t });
}
}
With this, you can simply invoke Foo
like:
var objSquare = new Square();
objSquare.InvokeFoo();
var objBar = new Bar();
objBar.InvokeFoo();
which works for every class. In this case, it will output:
Square
Bar