So I'm currently learning about foreach loops, enums and lists. Now, I have a class called Shoe and an enum called Color:
Code:
class Shoe
{
public Shoe(Color color, int age)
{
this.color = color; this.age = age;
}
public Color color;
public int age;
public string GetDescription()
{
return "This shoe is " + color + " and is " + age + " years old.";
}
}
enum Color
{
Black,
Red,
White,
Yellow,
Blue,
}
I Also have a class called LaceShoe that inherits from Shoe:
Code:
sealed class LaceShoe : Shoe
{
public LaceShoe(Color color, int age)
: base(color, age)
{
}
}
Ok , so here is the test i'm trying to do.
Code:
List<Shoe> shoesList2 = new List<Shoe>();
shoesList2.Add(new LaceShoe(Color.Yellow, 20));
shoesList2.Add(new Shoe(Color.Blue, 10));
shoesList2.Add(new LaceShoe(Color.Red, 40));
shoesList2.Add(new Shoe(Color.White, 80));
shoesList2.Add(new Shoe(Color.Blue, 30));
Shoe[] shoesarray = new Shoe[shoesList2.Count];
int y = 0;
foreach (Shoe shoe in shoesList2)
{
shoesarray[y] = shoe;
y++;
}
int b = 0;
foreach (LaceShoe shoe in shoesarray)
{
b++;
Console.WriteLine("This shoes array has " + " lace shoes");
}
But this doesn't work. It says unable to cast object of type shoe to type lace shoe. I'm not sure why it gives me that. I made a new list of type shoe and added 3 shoe objects and 2 LaceShoe objects to it. Then I went through all the shoes in the shoe list and populated the shoesarray with the shoes in the shoelist.
Then , All I want to do next is look for the LaceShoes in the shoesarray. Since the shoesarray got populated with all the shoe objects in the shoelist, shouldn't it also have the 2 shoelace objects of shoelist? And then, shouldn't I be able to get the amount of LaceShoes in my shoesarray? Which is 2?
Now keep in mind, I know how to fix this; All i have to do is do this instead:
Code:
foreach (Shoe shoe in shoesarray)
{
if (shoe is LaceShoe)
{
b++;
Console.WriteLine("This shoes array has " + b + " lace shoes");
}
}
All I want to know is WHY it gave me the error. Is it because my shoesarray is type Shoe and when I use foreach loops I can only do it of the type my collection is? But if that's the case, since LaceShoe is also a shoe, shouldn't I be able to check for Laceshoes is the foreach loop?