So let’s say we have a class named Car and three other classes (Opel , Volkswagen and Peugeot ) which inherits information from Car but in addition each class has a specific variable.
So I create a new List of Cars in which I add those three types CarOpel..etc.
Opel CarOpel = new Opel(parameters);
etc…
List<Car> Cars = new List<Car>();
Car.Add(CarOpel);
etc…
How can I access those specific variables from each class when I use the “foreach” statement
foreach ( Car car in Cars )
{
// how to convert *car* in *Opel* , *Volkswagen* or *Peugeot* to get that specific variable?
}
?
Other solution is to use
iskeywordIf you need to downcast your cars in order to do something it may suggest that your inheritance hierarchy is wrong or your method is not in the proper place. It probably should be a virtual method in
Carclass which is overridden in derived classes. Also consider reading about visitor pattern.