What C# feature will you use to keep common behaviors at one place and force clients to implement some others?

Answer: To have common behaviors at one place and force clients to implements others, we should use C# Abstract class and method feature. Abstract class is the class that contains common behaviors/methods and defer implementation of some methods to client’s class in inheritance.

Client class will be referred as a derived class. Client classes will be using the common methods defined in abstract class Car and implement some methods deferred by base class Car.

Let’s understand this scenario by an example and implementation:

In below code, Car class has some common methods – audioSystem() and airbags() that will be used by all client classes.

We will have two more abstract methods in the class Car i.e. mileage()and engine()that will be implemented by all client classes i.e. MarutiErtiga and MarutiBaleno cars.

Note that “abstrcat” is the keyword used before function to defer implementation to client classes.

//Abstract Class
abstract class Car
{
    //Have common methods in abstract class
    public void audioSystem() { Console.WriteLine("audioSystem"); }
    public void airbags() { Console.WriteLine("airbags"); }

    //Defer implementation to client class
    public abstract void mileage();
    public abstract void engine();
}

//Abstrac class Client
class MarutiErtiga : Car
{
    //implement mileage
    public override void mileage()
    {
        Console.WriteLine("17.5 kmpl");
    }

    //Implement engine
    public override void engine()
    {
        Console.WriteLine("1373 cc");
    }
}

class MarutiBaleno : Car
{
    //implement mileage
    public override void mileage()
    {
        Console.WriteLine("21.4 kmpl");
    }

    //Implement engine
    public override void engine()
    {
        Console.WriteLine("1197 cc");
    }
}

//Test program
   class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Maruti Ertiga");
            //Maruti ertiga object
            Car me = new MarutiErtiga();
            me.airbags();
            me.audioSystem();
            me.mileage();
            me.engine();
           
            Console.WriteLine("Maruti Baleno");
            Car mb = new MarutiBaleno();
            mb.airbags();
            mb.audioSystem();
            mb.mileage();
            mb.engine();

        }
    }

Output:

Maruti Ertiga
airbags
audioSystem
17.5 kmpl
1373 cc
Maruti Baleno
airbags
audioSystem
21.4 kmpl
1197 cc

Related Posts