Polymorphism- Specific action in different ways (C#)

Patel Dhiren
2 min readMay 25, 2023

--

Polymorphism is another fundamental concept in object-oriented programming (OOP) that allows you to objects of different classes to be treated as objects of a common base class. It enabled same name can perform different task under different scenarios.

Let’s continue with the example of a laptop to illustrate polymorphism in C#:

class Laptop
{
public virtual void PowerButtonPressed()
{
Console.WriteLine("Power button does nothing in the base laptop state.");
}
}

class OffStateLaptop : Laptop
{
public override void PowerButtonPressed()
{
Console.WriteLine("Laptop is switching on...");
// Logic for switching on the laptop
}
}

class OnStateLaptop : Laptop
{
public override void PowerButtonPressed()
{
Console.WriteLine("Laptop is switching off...");
// Logic for switching off the laptop
}
}

class Program
{
static void Main(string[] args)
{
Laptop laptop = new OffStateLaptop();
laptop.PowerButtonPressed();

laptop = new OnStateLaptop();
laptop.PowerButtonPressed();
}
}

In this example, we have a base class Laptop with a virtual method PowerButtonPressed(). The derived class OffStateLaptop overrides this method to handle the functionality of switching on the laptop when it is in the off state. Similarly, the derived class OnStateLaptop overrides the method to handle the functionality of switching off the laptop when it is already on.

In the Main method, we create an instance of the OffStateLaptop class and call the PowerButtonPressed() method, which triggers the specific behavior for switching on the laptop. Next, we create an instance of the OnStateLaptop class and call the same method, which triggers the behavior for switching off the laptop.

Advantages of Polymorphism:

  1. Code Reusability
  2. Maintainability

Thank you! I’m glad to hear that you’re enjoying the learning process. If you have any more questions or need further assistance, feel free to ask. Happy learning to you too!

--

--