Generic methods and inheritanc on non generic class

J

John B

If I have the following classes:

public abstract class Base
{
public abstract T CreateItem<T>() where T : Base;
}

public class Derived : Base
{
public override T CreateItem<T>()
{
return new Derived(); //Implicit cast error
}
}


Why does the CreateItem method in Derived fail as Derived inherits from
Base and therefore I would have thought the constraints satisfied.
If I try and explicit cast to T it fails with the error "Cannot convert
type Derived to T"
The only way it compiles is if I cast using the as operator.

Cheers

JB
 
M

Marc Gravell

The inheritence Derived : Base is unrelated to the "where" clause on a
generic method, since T is supplied by the *caller*, and must return
that T; e.g. I can declare ClassA : Base, and even ClassB : ClassA,
and then call (on a Derived instance) CreateItem<ClassB>(); CreateItem
then *must* return a ClassB, but isn't going to since Derived and
ClassB cannot be cast.

Perhaps a better option is:

public abstract class Base
{
public abstract T CreateItem<T>() where T : new() { return new
T();}
}

although at the end of the day, the caller could do that themselves!
Perhaps generics aren't the solution... what is the problem you are
trying to solve?

Marc
 
J

John B

Marc said:
The inheritence Derived : Base is unrelated to the "where" clause on a
generic method, since T is supplied by the *caller*, and must return
that T; e.g. I can declare ClassA : Base, and even ClassB : ClassA,
and then call (on a Derived instance) CreateItem<ClassB>(); CreateItem
then *must* return a ClassB, but isn't going to since Derived and
ClassB cannot be cast.
Of course. Doh!
Perhaps a better option is:

public abstract class Base
{
public abstract T CreateItem<T>() where T : new() { return new
T();}
}

although at the end of the day, the caller could do that themselves!
Perhaps generics aren't the solution... what is the problem you are
trying to solve?
Covariant return types :D

I can solve it with generics anyway but I had an abstract class that
creates an instance of another abstract base class and depending on the
concrete implementation it would be different types.
So I either specify the return type as the base and cast or using
generics strong type to the concrete class anyway so all is good.

Cheers,

JB
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top