Suppose I have a class Animal, and several sub-classes, Dog, Cat, Bird, etc.
Now I have a Person, who has an Animal. She wants to see if the pet store has an animal of the same type.
So I have:
Animal sampleAnimal;
List<Animal> listOfAnimals; // in our hypothetical pet store
When I try to do this (in C# 3.5):
Type typeWeWant = sampleAnimal.GetType();
foreach (var x in listOfAnimals) {
if (x is typeWeWant) { // error here
return true;
}
}
I get the error "typeWeWant is a variable but is used like a type."
Okay. How do I do this?
Keep in mind, our Person might have a CalicoCat, which is a subclass of Cat, and it should match against Cat. So using GetType.ToString() won't work. (Pets are not exactly what's going on in my case - if the code as written worked, I would be fine. I don't need to test both ways.)
I apologise if this has been asked anywhere already, but all I could find were questions regarding generics, which is not quite the case here.
EDIT: Thank you SO much for both the answers and the "duplicate" link! These are exactly what I needed and could not find!