aaa
aaa

Reputation: 31

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?

Upvotes: 0

Views: 151

Answers (2)

canton7
canton7

Reputation: 42225

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.

Upvotes: 3

EricSchaefer
EricSchaefer

Reputation: 26330

Your (non-generic) variant is returning an object of type BaseClass while the generic variant is returning an object of whatever T is (i.e. A or B or BaseClass).

Upvotes: 4

Related Questions