Search code examples
c#oopgenericsinheritancegeneric-programming

The purpose of using generic methods where generic is some base class


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?


Solution

  • Notice how your method returns an instance of T.

    Using generics, this is valid:

    A input = new A();
    A output = c.test(input);
    

    If we try and do the same with the version which just uses BaseClass:

    A input = new A();
    A output = c.test(input); // Error: can not assign instance of 'BaseClass' to 'A'
    

    This is, obviously, because test returns an instance of BaseClass. Instead we have to write:

    A input = new A();
    A output = (A)c.test(input);
    

    ... and we don't have any compile-time guarantees that test actually returns an instance of A in this case, and not an instance of B.