Polymorphism

C# Polymorphism

Polymorphism in C# refers to the ability of objects to take on different forms. It allows methods to behave differently based on the object that calls them, enabling flexibility and reusability in code.


Key Concepts of Polymorphism

  1. Compile-Time Polymorphism (Static Polymorphism)

    • Achieved through method overloading and operator overloading.

    • The behavior is determined at compile time.

  2. Run-Time Polymorphism (Dynamic Polymorphism)

    • Achieved through method overriding using inheritance.

    • The behavior is determined at runtime.


1. Compile-Time Polymorphism (Method Overloading)

Definition:

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

Example:

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;
    }
}

// Usage
Calculator calc = new Calculator();
Console.WriteLine(calc.Add(5, 3));       // Output: 8
Console.WriteLine(calc.Add(5.5, 3.3));   // Output: 8.8
Console.WriteLine(calc.Add(1, 2, 3));    // Output: 6

2. Run-Time Polymorphism (Method Overriding)

Definition:

  • A derived class overrides a base class method using the virtual and override keywords.

Example:


Polymorphism with Interfaces

  • Interfaces provide polymorphism by ensuring a class implements certain methods.

Example:


Key Terms

Term

Description

Method Overloading

Multiple methods with the same name but different signatures.

Method Overriding

Redefining a method in a derived class to change its behavior.

Virtual

Indicates that a method can be overridden in a derived class.

Override

Used in the derived class to override a virtual method.

Abstract

Defines a method without implementation in a base class, requiring derived classes to implement it.

Interface

Provides a contract for classes to implement methods, enabling polymorphism.


Differences Between Overloading and Overriding

Aspect

Overloading

Overriding

Definition

Same method name, different parameters.

Redefining a method in the derived class.

Polymorphism Type

Compile-time

Run-time

Keyword

No special keywords.

virtual, override, abstract

Class Relationship

Same class.

Requires inheritance.


Example Combining Overloading and Overriding

Example:


Summary

  • Polymorphism provides flexibility by allowing a single interface to represent different types of behavior.

  • Types:

    • Compile-Time: Method overloading and operator overloading.

    • Run-Time: Method overriding using inheritance.

  • Use polymorphism to enhance code reusability, maintainability, and extensibility.

Polymorphism is a cornerstone of object-oriented programming, ensuring better design and reduced redundancy.