JNappi
JNappi

Reputation: 1585

Create a Generic List of Generic objects in C#

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.

Upvotes: 0

Views: 88

Answers (1)

Tim S.
Tim S.

Reputation: 56576

This is possible if you use a covariant interface:

internal interface IGenericThing<out T>
{
}

internal class GenericThing<T> : IGenericThing<T>
{
}

void Main()
{
    var thing1 = new GenericThing<ThisThing>();
    var thing2 = new GenericThing<ThatThing>();

    var thing3 = new GenericThing<SomethingElse>();

    var thingList = new List<IGenericThing<ISomething>>() {thing1, thing2};
}

Note that this is only possible if T is only used as an output in IGenericThing<T>, never as an input! (it being unused, as in my example, is also permissible; although, obviously, useless)

Upvotes: 4

Related Questions