Is there any purpose of using generic methods where T generic is base class? For example
class A: BaseClass
{
}
class B : BaseClass
{
}
class C
{
public T test<T> (T aa) where T : BaseClass
{
}
}
why do not just write in this way?
class C
{
public BaseClass test (BaseClass aa)
{
}
}
What gives us generic in this situation?
Notice how your method returns an instance of
T.Using generics, this is valid:
If we try and do the same with the version which just uses
BaseClass:This is, obviously, because
testreturns an instance ofBaseClass. Instead we have to write:... and we don't have any compile-time guarantees that
testactually returns an instance ofAin this case, and not an instance ofB.