I have a generic class for which I would like to create a generic list, where the underlying classes implement the same interface. However, not all implement the given interface.
An example would be easier than describing the problem.
internal interface ISomething
{
}
internal class ThisThing : ISomething
{
}
internal class ThatThing : ISomething
{
}
internal class SomethingElse
{
}
internal class GenericThing<T>
{
}
internal class DoThings
{
void Main()
{
var thing1 = new GenericThing<ThisThing>();
var thing2 = new GenericThing<ThatThing>();
var thing3 = new GenericThing<SomethingElse>();
**var thingList = new List<GenericThing<ISomething>>() {thing1, thing2};**
}
}
I'm unable to create the thingList. Is there a way to cast the two things that implement the same interface into a generic collection, while still preserve the GenericThing class not to be constrained to the interface.
thing3to theList?GenericThingis not covariant with respect to its generic argument, so this won't work.An example would be easier than describing the problemI wouldn't be so sure of that.