Search code examples
c#abstract-classderived-classbase-class

Run same method of each derived type sequentially c#


I have below code with IVehicle interface having TestDrive method. There is an abstract class - Vehicles, which implements IVehicle & has a property TestDriveTime.

There are a number of child classes like Car, Scooter, etc (about 25 such child classes). which derive from Vehicle & have their own implementations of TestDrive().

Please help me with my questions -

  1. If I have to run each of these TestDrive sequentially, is my code in Main() correct?
  2. If All the child objects are using the same TestDriveTime, how shall I set it?

.

public interface IVehicle 
{  
    void TestDrive();
}

public abstract class Vehicle : IVehicle
{
    public DateTime TestDriveTime { get; set; }
    abstract public void TestDrive();
}

public class Car : Vehicle
{
    public override void TestDrive()
    {
        // code for car testDrive
        // uses TestDriveTime
    }
}

public class Scooter : Vehicle
{
    public override void TestDrive()
    {
        // code for car testDrive
        // uses TestDriveTime same as car
    }
}

static void Main(string[] args)
{
    IVehicle vehicle = null;
    // 1. need to set the TestDriveTime which can be used for vehicles of all types. 

    vehicle = new Car();        
    vehicle.TestDrive();

    // 2. Need to run the TestDrive for all vehicles sequentially

    vehicle = new Scooter();
    vehicle.TestDrive();
}

Solution

  • 1) Declare a list:

    List<IVehicle> vehicles = new List<IVehicle>();
    

    then add all of your vehicles:

    vehicles.Add(new Car());
    vehicles.Add(new Scooter());
    

    and iterate:

            foreach (IVehicle v in vehicles)
                v.TestDrive();
    

    2) You can set TestDriveTime and use it for all of your objects:

    v.TestDrive(TestDriveTime);

    Change the method declaration to: IVehicle.TestDrive(DateTime testDriveTime)