1

I'm trying to return a list derived classes (RedThingSets and BlueThingSets) as a list of their base (ThingSets) class so that I can have a more generic function returning them (this is just an example to illustrate).

(This is not actual code)

public abstract class ThingSet 
{
    public List<Thing> Things;
}

public class RedThingSet : ThingSet {}

public class BlueThingSet : ThingSet {}


public void MahClass()
{

    public List<RedThingSet> RedThingsList = new List<RedThingSet>();
    public List<BlueThingSet> BlueThingsList = new List<BlueThingSet>();

    public List<ThingSet> GetThingSet( bool giveMeTheBlue )
    {
        if ( giveMeTheBlue )
        {
            return BlueThingsList;
        }
        else
        {
            return RedThingsList;
        }
    }
}

Is this possible?

I've tried using as like this: return BlueThingsList as List<ThingSet>;

And I've tried casting it directly like this: return (List<ThingSet>) BlueThingsList;

But neither are working,

Am I just approaching this entirely wrong?

  • 1
    Does this answer your question? [How to cast a list of a base type to list of the derived type](https://stackoverflow.com/questions/15274146/how-to-cast-a-list-of-a-base-type-to-list-of-the-derived-type) It talks about going the other direction, but the issue is the same: there's no reference conversion from a list of one type to a list of the other (a reference conversion between the *element* types does not enable a reference converstion between *list* types). – madreflection Feb 12 '21 at 16:49
  • 4
    The problem is, you're trying to return the concrete `List` object. So you return the `BlueThingsList` as a `List` to the caller, they then try to add a `RedThingSet` to it, but at heart, it's still a list that's only meant to contain `BlueThingSet`s. See the problem? You can return `IEnumerable` if you only expect the callers to read, not modify. – Damien_The_Unbeliever Feb 12 '21 at 16:50
  • 1
    See Eric Lipper's answer to: [why does explicit cast for generic list not work](https://stackoverflow.com/a/9891849/880990). – Olivier Jacot-Descombes Feb 12 '21 at 16:59

0 Answers0