I'm studying programming right now and I had to create a snake game.
In the game, there are around 5 possible consumables for the snake and I decided to put every new Consumable in a Consumable array.
Now I wanted to iterate with foreach loops through the array and do something like:
foreach (Apple apple in consumables)
{
renderer.DrawApple(apple);
}
However when there are different objects in the array like an Apple and a SegmentRemover (which is possible, because they inherit from the Consumable class), then the compiler iterates over the SegmentRemover as well and I get an invalid cast exception.
I thought since I'm declaring in the foreach loop that I only want to iterate over Apple objects, that it should work.
Are there any easy ways to get around this? Preferably without things like var or typeof, since I'm not allowed to use these yet.