Generic classes, inheritance and polimorphism

G

Guest

OK, this was hard to explain on a short title. Sorry.

I have an abstract class (MustInherit) named Base, and a generic collection
class named ColBase which can only take Base and derived classes as it's
type.

I also have an indefinite number of classes that inherit Base. I want to
make a method on Base that returns a ColBase(of Base), but instead of
ColBase(of Base) use the derived class.

So if I have a class named Inherited, when I call Inherited.GetColBase it
returns a ColBase(of Inherited) and not a ColBase(of Base).

Do you know if this is possible, and if so, how to do it? Thanks a lot,

Joaquín Raya
 
B

Barry Kelly

Joaquin said:
OK, this was hard to explain on a short title. Sorry.

I have an abstract class (MustInherit) named Base, and a generic collection
class named ColBase which can only take Base and derived classes as it's
type.

I also have an indefinite number of classes that inherit Base. I want to
make a method on Base that returns a ColBase(of Base), but instead of
ColBase(of Base) use the derived class.

So if I have a class named Inherited, when I call Inherited.GetColBase it
returns a ColBase(of Inherited) and not a ColBase(of Base).

It sounds like what you are looking for is generic type argument
covariance. C# does not support it, but .NET does support it when the
type parameter appears as a type for a return value only (covariance is
only safe as an "output-only" or return value, similarly contravariance
is only safe as an input-only argument).

Short answer, you'll have to create specific methods in the
descendant(s) that explicitly cast from Base to Inherited.

-- Barry
 
E

evan

this should be a valid workaround... the compiler may complain if
your generic collection class has a constraint on it (ie.. T must be a
subclass of Base).. in that case you just need to add the constraint
on the generic methods as well

public abstract class Base()
{
protected IList<T> GetNewList() where T : Base
{
return CreateList(this);
}

private IList<T> CreateList(T objectToCreateListFor) where T : Base
{
return new List<T>();
}
}
 

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