Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How can I return an array of different elements that inherit from the same class?

I have a class A from which B and C inherit.
I have two lists: listB and listC, of the respective types.

I want to make a method that returns the two lists inside an array, like so:

public override List<A>[] GetAllItems()
{
    return new List<A>[2]
    {
        listB,
        listC
    };
}

However, when I try this approach, I get the following error, because I try to convert the inherited types incorrectly.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Cannot implicitly convert type ‘System.Collections.Generic.List<Lae.B>’ to ‘System.Collections.Generic.List<Lae.A>’ [Assembly-CSharp]csharp(CS0029)

Is there some way to create this array without converting the elements?


Note: I am not using a struct or class, because I want the array to be of various sizes based on logic above.

>Solution :

public List<A>[] GetAllItems()
{
    var result = new List<A>[2] {
        listB.Cast<A>().ToList(),
        listC.Cast<A>().ToList(),
    };
    
    return result;
}

If you need to return array of Lists – easiest way is to use Cast linq extension method.

In reference to the comments you have to remember that if you modify listB or listC, the change won’t be reflected in the casted collections.

Anyway, if you need to have an access to the original listB / listC collections references, you can use IEnumerable instead of List in order to not be forced to "materialize" the results. Example:

public IEnumerable<A>[] GetAllItems()
{
    return new IEnumerable<A>[] {
        listB,
        listC,
    };
}

Now when you access eg. allItems[0] it will reference to the original listB collection.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading