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.
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.
listB.Cast<A>().ToList(), unless that is what you mean by "converting the elements" - I don't class a cast as a conversion in this sense because yourBs in yourlistBremainBs (look like A but can be cast back to B) rather than becoming As (A cannot be cast to B) but your opinion may differ(List<B>,List<C>)instead..GettAllItemsreturn aIReadOnlyList<A>[]? Or does each list need to remain mutable when accessed via the array?object o = new StringBuilder(); (o as StringBuilder).Append("Hello world");- it is still a StringBuilder insideo, it still has its text "Hello world", and it can be treated as a stringbuilder at any time by castingoto a StringBuilder. It is of course, a massive pain in the ass to cast all the time and makes for ugly code; you'd probably want to cast back.. But if you were going to do that you might as well just use the tuple I suggested and skip that "cast it all as A just to get it out of the method then uncast as B/C again"