I have the classes
Interface IVehicle
{
int numberOfWheels;
bool CanCross(string obstacle);
// etc
}
class Car : IVehicle
{
public int numberOfWheels = 4;
public bool CanCross(string obstacle)
{
switch(obstacle)
{
case "river":
return false;
case "grass":
return true;
// etc
}
}
}
class RaceCar: Car
{
public int numberOfWheels = 4;
public bool CanCross(string obstacle)
{
switch(obstacle)
{
case "river":
return false;
case "grass":
return false;
// etc
}
}
}
And then I have the method:
public object Foo(IVehicle vehicle, string obstacle)
{
if(vehicle.CanCross(obstacle)==false)
{
if(vehicle is Car)
return Foo(new RaceCar(), obstacle);
else if(vehicle is RaceCar)
return Foo(new OldCar(), obstacle);
// etc
else
return null;
}
// implementation
return someObject;
}
note that if the vehicle cannot cross the obstacle I recursively call the same method again in order to try with a different vehicle. My question is why if vehicle = SpeedCar then if (vehicle is Car) evaluates to true ? Probably because it inherits from it. How could I check if the vehicle is a SpeedCar but not a Car. I now I could call the ToString() method then do a regex but then if I rename my classes I will break my code…
In other words if the vehicle that I pass cannot cross and it happens to be a Car or SpeedCar I will go into an infinite loop…
1 Answer