I have a class with a member for a list of objects. Lets say i have an Animal base class and subtypes of Cat and Dog. The list will always contain only Dogs or only Cats but i do not know up front.
class MyClass {
public readonly List<Animal> Data = new();
public void MethodForDogs()
{
Data.Add(new Dog());
}
public void MethodForCats()
{
Data.Add(new Cat());
}
public void DoSomething()
{
HelperClass.DoIt(Data);
}
}
class HelperClass {
public static void DoIt(List<Animals> data) {
if (data[0].GetType() == typeof(Cat) ) {
var arrayCats = new Cat[data.Count];
int i = 0;
foreach (Animal item in data) {
arrayCats[i++] = (Cat) item;
}
// use arrayCats
..
}
else if (data[0].GetType() == typeof(Dog) {
// same, then use arrayDogs
..
}
}
}
what did NOT work was a direct cast, like
var arrayCats = (Cat[])data.ToArray();
even though i can check that all members are Cats. Is there a more elegant way to do this?