Polymorphism


In this article we are going to discuss Polymorphism in C#. There are many blogs, articles are available on the internet regarding Polymorphism but in this particular article I will try to explain to you with as much as simplest and realistic examples so you can get a clear idea of the Polymorphism use in C#.

Polymorphism Introduction

  1. Polymorphism is one of the four fundamental principles of object-oriented programming (OOP).
  2. Polymorphism is a Greek word meaning "one name many forms." "Poly" means many, and "morph" means forms.
  3. The term polymorphism means many Forms and allows objects to be treated as instances of their parent class rather than their actual class.
  4. This concept enables a single function or method to work in different ways depending on the type of input or the object it is acting upon.

It is the combination of two words Poly + Morphs = Many Forms.

PolyMorphism

Real World Example of Polymorphism in C#

A good example of polymorphism is Men in society. A Men can do many different things. He can be a Husband, a Father, and have a job, all at the same time. Even though He does different things, He's still just one person. This is like polymorphism because He takes on different roles.

PolyMorphism

Benefits of Polymorphism

  1. Code Reusability - Polymorphism allows methods to use objects of different classes, promoting code reusability.
  2. Maintainability - It helps in making the code more maintainable by allowing changes in the method implementation without affecting the code that uses the method.
  3. Extensibility - New classes can be introduced with minimal changes to the existing codebase.

Real life Example of Polymorphism

The best example of polymorphism is ourselves. For example, when we hear something interesting or something which is good for us, we feel happy. And when we hear something which is not good for us, we feel sad. Suppose, you asked your father to purchase a car, and if your father purchases a car for you then you will feel happy. And if your father says that I am not going to purchase a car for you, then you will feel sad. So, you are the same person, when you received something good, you feel happy and when you receive something which is not good, you feel sad. This is called polymorphism.

Example

In this example we will see function with same name but have multiple forms.

public class MathOperations
{
    // Method to add two integers
    public int Add(int a, int b)
    {
        return a + b;
    }

    // Method to add two strings
    public string Add(string a, string b)
    {
        return a + b;
    }
 }

// Usage
class Program
{
    static void Main()
    {
        MathOperations math = new MathOperations();
        Console.WriteLine(math.Add(1, 2));        
        Console.WriteLine(math.Add("Rohatash", "Kumar"));    
       
    }
}

In the above example, you will see function with same named as Add() but have multiple forms

Output

PolyMorphism

Real World Example of PolyMorphism - Payment System

In an e-commerce platform, different payment methods (like CreditCard, PayPal, and BankTransfer) can be used. All these payment methods have a common behavior of processing a payment, but the way they process the payment might be different.

Step 1: Define the Base Class and Derived Classes

// Base class
public abstract class Payment
{
    public abstract void ProcessPayment(decimal amount);
}

// Derived class for Credit Card payment
public class CreditCardPayment : Payment
{
    public override void ProcessPayment(decimal amount)
    {
        Console.WriteLine($"Processing credit card payment of {amount:C}");
        // Logic for processing credit card payment
    }
}

// Derived class for PayPal payment
public class PayPalPayment : Payment
{
    public override void ProcessPayment(decimal amount)
    {
        Console.WriteLine($"Processing PayPal payment of {amount:C}");
        // Logic for processing PayPal payment
    }
}

// Derived class for Bank Transfer payment
public class BankTransferPayment : Payment
{
    public override void ProcessPayment(decimal amount)
    {
        Console.WriteLine($"Processing bank transfer payment of {amount:C}");
        // Logic for processing bank transfer payment
    }
}

Step 2: Using Polymorphism

public class PaymentProcessor
{
    public void ProcessPayment(Payment payment, decimal amount)
    {
        payment.ProcessPayment(amount);
    }
}

class Program
{
    static void Main(string[] args)
    {
        PaymentProcessor paymentProcessor = new PaymentProcessor();

        // Using polymorphism to handle different payment methods
        Payment creditCardPayment = new CreditCardPayment();
        Payment payPalPayment = new PayPalPayment();
        Payment bankTransferPayment = new BankTransferPayment();

        // Process payments
        paymentProcessor.ProcessPayment(creditCardPayment, 100.00m);
        paymentProcessor.ProcessPayment(payPalPayment, 200.00m);
        paymentProcessor.ProcessPayment(bankTransferPayment, 300.00m);
    }
}

Explanation

  1. Base Class Payment - This is an abstract class that defines the ProcessPayment method.
  2. Derived Classes - CreditCardPayment, PayPalPayment, and BankTransferPayment inherit from the Payment class and provide their own implementation of the ProcessPayment method.
  3. Polymorphism in Action - In the Main method, different types of payments are created (CreditCardPayment, PayPalPayment, BankTransferPayment) but they are all treated as Payment objects. The PaymentProcessor class processes the payments without needing to know the specific type of payment method.

Types of Polymorphism in C#

In C#, polymorphism can be categorized into two main types.

  1. Compile-Time Polymorphism (Static Polymorphism)
  2. Runtime Polymorphism (Dynamic Polymorphism)
PolyMorphism

1. Compile-Time Polymorphism (Static Polymorphism)

This type of polymorphism is resolved during compilation. Compile-time polymorphism is achieved through:

  1. Method overloading
  2. Operator overloading

1. Runtime-Time Polymorphism (Dynamic Polymorphism)

This type of polymorphism is resolved during Runtime. Run-time polymorphism is achieved through:

  1. Method Overriding

Next