Good afternoon all, I'm learning to work with 'Lists' I've set up a list of 'zooAnimals' and in the list i've added objects as they have been created.
zooAnimals = new List<Animal>();
newcat1 = new Cat(cat1, catPen, fircat);
newcat2 = new Cat(cat2, catPen, seccat);
newtig1 = new Tiger(tiger1, tigerPen, firtig);
newtig2 = new Tiger(tiger2, tigerPen, sectig);
zooAnimals.Add(newcat1);
zooAnimals.Add(newcat2);
zooAnimals.Add(newtig1);
zooAnimals.Add(newtig2);
I would like to now step through the list to perform certain actions when a button is pressed. For example - the form has a number of buttons on it - 1 being for individual groups of animals to eat(). I tried with
foreach (Cat thisCat in zooAnimals)
{
if (thisCat.hunger == 7)
{
thisCat.hunger = thisCat.hunger - 5;
}
}
but this code throws an InvalidCast Exception...... Unable to cast object of type 'Zoo_Animals.Tiger' to type 'Zoo_Animals.Cat'. Is there a way of stepping through the list to do this ? Thanks in advance ! Neil