How are you?
We are from Argentina
Sorry but my english isn't very good.
I have got an exercise to resolve with OOP and we are looking for the best way to solve it
The problem to solve is count the number of instances of any subtype (Car, Truck) in a supertype collection (Vehicle)

C# code
IList<Vehicle> vehicles = new List<Vehicle>();
Car aCar = null;
Truck aTruck = null;
aCar = new Car();
vehicles.Add(aCar);
aCar = new Car();
vehicles.Add(aCar);
aCar = new Car();
vehicles.Add(aCar);
aTruck = new Truck();
vehicles.Add(aTruck);
aTruck = new Truck();
vehicles.Add(aTruck);
// 3 cars
// 2 trucks
int cars = 0;
int trucks = 0;
foreach(Vehicle v in vehicles) {
if(v is Car){
cars++;
} else if(v is Truck){
trucks++;
}
}
is there a better way to solve this problem, without using clause "is Type"?
Cheers!
Fernando López Guevara


Sign In
Create Account

Back to top









