You don't want to call a generic method here. Once you enter TestGeneric<T>
, even if T
is MyClass2
as you want, you can't have written any code against MyClass2
(or even MyClass
, unless you add a restriction on T
) so it doesn't help!
You certainly don't need to go down the route of reflection or dynamic
.
Most obvious way to do this: put the class-specific behaviour in the class itself:
class MyClass
{
public virtual void Test()
{
// Behaviour for MyClass
}
}
class MyClass2 : MyClass
{
public override void Test()
{
// Behaviour for MyClass2
}
}
private void Foo(MyClass cl)
{
cl.Test();
}
Next-best: branch code depending on the type passed:
private void Foo(MyClass cl)
{
if (cl is MyClass2)
{
Test((MyClass2)cl);
}
else
{
Test(cl);
}
}
private void Test(MyClass cl)
{
// Behaviour for MyClass
}
private void Test(MyClass2 cl2)
{
// Behaviour for MyClass2
}
In both these cases you can write code directly against MyClass2
(or MyClass
) without having to do any reflection, use dynamic
, or... whatever you were planning to do in your generic method - branch on typeof(T)
?