CHASH Tutorial



C# POLYMORPHISM


C# Polymorphism

Polymorphism means "many forms". In C#, it allows methods to have different implementations depending on the object that is calling them. This is one of the core concepts of Object-Oriented Programming (OOP).

💡 Real-life example:
Think of a printer. Whether it's printing a Word document or a PDF, the Print() function is called — but the way it prints differs depending on the document type.

Types of Polymorphism in C#

  • Compile-time Polymorphism (Method Overloading)
  • Run-time Polymorphism (Method Overriding)

1. Method Overloading (Compile-time Polymorphism)

You can define multiple methods with the same name but different parameters.

class Calculator
{
    public int Add(int a, int b)
    {
        return a + b;
    }

    public double Add(double a, double b)
    {
        return a + b;
    }
}

class Program
{
    static void Main()
    {
        Calculator calc = new Calculator();
        Console.WriteLine(calc.Add(3, 4));     // Output: 7
        Console.WriteLine(calc.Add(3.2, 4.8)); // Output: 8
    }
}
  

2. Method Overriding (Run-time Polymorphism)

With inheritance, a derived class can override a base class method using the override keyword.

class Animal
{
    public virtual void Sound()
    {
        Console.WriteLine("Animal makes a sound");
    }
}

class Dog : Animal
{
    public override void Sound()
    {
        Console.WriteLine("Dog barks");
    }
}

class Cat : Animal
{
    public override void Sound()
    {
        Console.WriteLine("Cat meows");
    }
}

class Program
{
    static void Main()
    {
        Animal myAnimal;

        myAnimal = new Dog();
        myAnimal.Sound();   // Output: Dog barks

        myAnimal = new Cat();
        myAnimal.Sound();   // Output: Cat meows
    }
}
  
🧠 Note: Polymorphism enables one interface to be used for a general class of actions.

Difference: Overloading vs Overriding

Feature Overloading Overriding
Occurs Compile time Run time
Inheritance Not required Required
Keyword used None virtual / override
✔️ Best Practice:
Use polymorphism to write flexible and maintainable code that can adapt to future changes.

🌟 Enjoyed Learning with Us?

Help others discover Technorank Learning by sharing your honest experience.
Your support inspires us to keep building!

Leave a Google Review