The problem is that the two lists aren't
covariant:
Quote:
In object-oriented programming, a covariant return type of a method is one that can be replaced by a "narrower" type when the method is overridden in a subclass. A notable language in which this is a fairly common paradigm is C++. C# does not support return type covariance.
(
Covariant return type - Wikipedia[
^])
What that basically means is that if you construct collections:
class Animal {...}
class Ape : Animal {...}
class Feline : Animal {...}
List<Ape> apes = new List<Ape>();
List<Feline> cats = new List<Feline>();
List<Animal> animals = new List<Animal>();
Then because an Ape is an Animal, you can add a new species to either collection:
Ape newSpecies = new Ape("Pans Sapiens");
apes.Add(newSpecies);
animals.Add(newSpecies);
But if you try to add it to the Felines:
cats.Add(newSpecies);
You will get a compilation error:
Argument 1: cannot convert from 'GeneralTesting.frmMain.Ape' to 'GeneralTesting.frmMain.Feline'
And that is what you would expect.
But ... if you could do what you want, you could do this:
Ape newSpecies = new Ape("Pans Sapiens");
animals = cats;
animals.Add(newSpecies);
And you would have an Ape in your Feline collection - which means your application will crash later on when you try to use it.
You can add all the items:
animals = new List<Animal>();
List<Ape> apes = new List<Ape>();
List<Feline> cats = new List<Feline>();
...
animals.AddRange(apes);
animals.AddRange(cats);
Or even explicitly:
animals = new List<Animal>();
List<Ape> apes = new List<Ape>();
List<Feline> cats = new List<Feline>();
...
animals.AddRange(apes.ConvertAll(x => (Animal)x));
animals.AddRange(cats.ConvertAll(x => (Animal)x));
But you can't assign items which aren't covariant.