0

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.

4
  • 7
    So, what exactly is your question? Commented Jul 24, 2014 at 20:31
  • Are you wanting to add thing3 to the List? Commented Jul 24, 2014 at 20:33
  • 3
    GenericThing is not covariant with respect to its generic argument, so this won't work. Commented Jul 24, 2014 at 20:35
  • An example would be easier than describing the problem I wouldn't be so sure of that. Commented Jul 24, 2014 at 20:35

1 Answer 1

4

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)

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.