Reputation: 13
I'm making a game for a school project and I've run into a problem. The teacher requires that I use polymorphism in the code so basically, I have two classes, X and Y and they inherit from the abstract base class K.
I have a list for K objects so that objects of X and Y can be put in the list.
So the problem is that I want to run through the list with a foreach
loop but only check the X objects.
foreach ( X object in list)...
The game crashes as soon as an X object is created and I don't understand why!
foreach (GoldCoin gc in powerUps.ToList())
{
if (gc.IsAlive)
{
player.speedY = 3;
}
else
{
powerUps.Remove(gc);
}
The error message said
System.InvalidCastException: 'Couldn't convert an object of the class X to the class Y.'
Upvotes: 0
Views: 192
Reputation: 216353
From your pseudocode, it seems that you are forcing every object in the list to be an object of type X. But if the list contains also objects of type Y then you cannot assign that object to an instance of X
Suppose your class are:
class K
{
public int value {get;set;}
}
class X : K
{
public string Name { get; set; }
}
class Y : K
{
public decimal money { get; set; }
}
void Main()
{
List<K> elements = new List<K>();
elements.Add(new X { Name = "Steve" });
elements.Add(new Y {money = 100});
// This cannot work, the second element is a Y and doesn't have a Name property
// foreach(X obj in elements)
// Console.WriteLine(obj.Name);
// This works because only elements of type X are retrieved by the enumeration
foreach(X obj in elements.OfType<X>())
Console.WriteLine(obj.Name);
}
Upvotes: 2