List to contain objects that derive from a generic base class

A

alastair g

I have a generic base class and need a list to contain different types
of objects that derive from this.

Public class genericBase<T> where T: ConfigBase{}

I have tried :
List<genericBase<ConfigBase>> _objectTypes

but when I try to add to it using:
ObjectTypes.Add((ObjectType<ObjectConfigBase>)UI);

I get a type conversion exception. Any ideas?
 
J

Jon Skeet [C# MVP]

I have a generic base class and need a list to contain different types
of objects that derive from this.

Public class genericBase<T> where T: ConfigBase{}

I have tried :
List<genericBase<ConfigBase>> _objectTypes

but when I try to add to it using:
ObjectTypes.Add((ObjectType<ObjectConfigBase>)UI);

I get a type conversion exception. Any ideas?

Well, I know what's wrong - C# generics don't support covariance/
contravariance, and ObjectType<ObjectConfigBase> isn't convertible to
ObjectType<ConfigBase>.

The *answer* to it really depends on what you need to do, and why.

Jon
 
A

alastair g

Well, I know what's wrong - C# generics don't support covariance/
contravariance, and ObjectType<ObjectConfigBase> isn't convertible to
ObjectType<ConfigBase>.

The *answer* to it really depends on what you need to do, and why.

Jon

ok, thanks. Need to rethink my approach then. Simplest would just be
to use an ArrayList and allow it to contain any object. I can always
validate what I put into it.
 

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