Home ยป C# Polymorphism : A Tutorial

C# Polymorphism : A Tutorial

by wskandot71

Polymorphism is one of the four fundamental concepts of Object-Oriented Programming (OOP) in C#.

It allows methods to have multiple forms, enabling code flexibility, reusability, and scalability.

C# supports two types of polymorphism:

  1. Compile-time polymorphism (Method Overloading)
  2. Runtime polymorphism (Method Overriding)

This tutorial covers:

  • What is Polymorphism?
  • Method Overloading (Compile-Time Polymorphism)
  • Method Overriding (Runtime Polymorphism)
  • Using base and virtual Keywords
  • Abstract Classes and Polymorphism
  • Interfaces and Polymorphism
  • Best Practices for Using Polymorphism

1. What is Polymorphism?

Polymorphism allows objects of different classes to be treated as objects of a common base class. It enhances code flexibility by allowing methods to behave differently based on the calling context.

Example: A Single Method Behaving Differently

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

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

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

class Program
{
    static void Main()
    {
        Animal myAnimal1 = new Dog();
        Animal myAnimal2 = new Cat();

        myAnimal1.MakeSound(); // Output: Dog barks.
        myAnimal2.MakeSound(); // Output: Cat meows.
    }
}
  • The same method MakeSound() behaves differently depending on the object (Dog or Cat).
  • This is an example of runtime polymorphism.

2. Method Overloading (Compile-Time Polymorphism)

Method overloading allows multiple methods with the same name but different parameters within the same class.

Example: Method Overloading

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

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

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

class Program
{
    static void Main()
    {
        Calculator calc = new Calculator();
        
        Console.WriteLine(calc.Add(2, 3));        // Calls Add(int, int)
        Console.WriteLine(calc.Add(2.5, 3.5));    // Calls Add(double, double)
        Console.WriteLine(calc.Add(1, 2, 3));     // Calls Add(int, int, int)
    }
}

Output:

5
6.0
6
  • Same method name (Add) performs different tasks based on parameter type and count.
  • This is an example of compile-time polymorphism.

3. Method Overriding (Runtime Polymorphism)

Method overriding allows a derived class to modify a method from its base class.

Example: Using override to Modify Behavior

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

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

class Program
{
    static void Main()
    {
        Animal myAnimal = new Dog();
        myAnimal.MakeSound(); // Output: Dog barks.
    }
}
  • The base class method (MakeSound()) is overridden in the Dog class.
  • The override keyword is required to modify the method.

4. Using base and virtual Keywords

  • The virtual keyword marks a method as overrideable.
  • The override keyword modifies the base class method in a derived class.
  • The base keyword allows access to the base class method.

Example: Using base to Call Parent Class Method

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

class Dog : Animal
{
    public override void MakeSound()
    {
        base.MakeSound(); // Calls base class method
        Console.WriteLine("Dog barks.");
    }
}

class Program
{
    static void Main()
    {
        Dog myDog = new Dog();
        myDog.MakeSound();
    }
}

Output:

Animal makes a sound.
Dog barks.
  • The base.MakeSound() calls the parent method before the child method runs.

5. Abstract Classes and Polymorphism

An abstract class cannot be instantiated and requires derived classes to implement abstract methods.

Example: Using Abstract Classes

abstract class Shape
{
    public abstract void Draw(); // Abstract method (must be implemented)
}

class Circle : Shape
{
    public override void Draw()
    {
        Console.WriteLine("Drawing a Circle.");
    }
}

class Rectangle : Shape
{
    public override void Draw()
    {
        Console.WriteLine("Drawing a Rectangle.");
    }
}

class Program
{
    static void Main()
    {
        Shape myShape1 = new Circle();
        Shape myShape2 = new Rectangle();

        myShape1.Draw(); // Output: Drawing a Circle.
        myShape2.Draw(); // Output: Drawing a Rectangle.
    }
}
  • Abstract methods enforce polymorphic behavior in derived classes.

6. Interfaces and Polymorphism

An interface defines a contract that must be implemented by classes.

Example: Using Interfaces for Polymorphism

interface IAnimal
{
    void MakeSound(); // Interface method
}

class Dog : IAnimal
{
    public void MakeSound()
    {
        Console.WriteLine("Dog barks.");
    }
}

class Cat : IAnimal
{
    public void MakeSound()
    {
        Console.WriteLine("Cat meows.");
    }
}

class Program
{
    static void Main()
    {
        IAnimal myDog = new Dog();
        IAnimal myCat = new Cat();

        myDog.MakeSound(); // Output: Dog barks.
        myCat.MakeSound(); // Output: Cat meows.
    }
}
  • Interfaces allow multiple classes to implement the same method differently.

7. Best Practices for Using Polymorphism

Use Method Overloading for Simplicity

class Printer
{
    public void Print(string text) { Console.WriteLine(text); }
    public void Print(int number) { Console.WriteLine(number); }
}
  • Improves code readability and reduces method names.

Use Method Overriding for Flexible Behavior

class Vehicle { public virtual void Start() { Console.WriteLine("Vehicle starts."); } }
class Car : Vehicle { public override void Start() { Console.WriteLine("Car starts."); } }
  • Ensures correct behavior for different types.

Use base Keyword to Extend Parent Functionality

class Dog : Animal
{
    public override void MakeSound()
    {
        base.MakeSound();
        Console.WriteLine("Dog barks.");
    }
}
  • Prevents redundant code duplication.

Use Interfaces for Decoupling Code

interface IShape { void Draw(); }
class Circle : IShape { public void Draw() { Console.WriteLine("Drawing Circle."); } }
  • Enhances flexibility and maintainability.

Conclusion

  • Polymorphism allows methods to behave differently based on the object type.
  • Method Overloading provides multiple versions of a method.
  • Method Overriding allows a derived class to redefine a method.
  • Abstract classes and interfaces enforce polymorphic behavior.
  • Polymorphism enhances code flexibility, reusability, and scalability.

You may also like

Adblock Detected

Please support us by disabling your AdBlocker extension from your browsers for our website.