By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
454,996 Members | 1,095 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 454,996 IT Pros & Developers. It's quick & easy.

Generic methods and inheritanc on non generic class

P: n/a
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
Feb 5 '07 #1
Share this Question
Share on Google+
2 Replies


P: n/a
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

Feb 5 '07 #2

P: n/a
Marc Gravell wrote:
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
Marc
Feb 5 '07 #3

This discussion thread is closed

Replies have been disabled for this discussion.