Polymorphism in C#

Mannan Ul Haq
0

Polymorphism, meaning "having many forms", is a crucial concept in object-oriented programming (OOP). It allows objects of different types to be treated as objects of a common base type. This facilitates writing generalized code which can work with objects in a more flexible and extensible way, leading to a single action being performed in multiple ways.


Polymorphism is achieved through two main mechanisms in C#: compile-time polymorphism (static polymorphism) and runtime polymorphism (dynamic polymorphism).

1. Compile-Time Polymorphism (Static Polymorphism):

Compile-time polymorphism is achieved through method overloading and operator overloading. Method overloading allows you to define multiple functions with the same name but different parameters. The appropriate method is selected based on the arguments at compile time. Operator overloading allows you to redefine the behavior of operators for user-defined types.


Example of function overloading:


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

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


In this example, the `Add` method is overloaded to handle both integer and floating-point arguments. The appropriate version of the method is selected based on the argument types at compile time.


2. Runtime Polymorphism (Dynamic Polymorphism):

Runtime polymorphism is achieved through inheritance (method overriding) and interface. Inheritance allows you to create a hierarchy of classes, where derived classes inherit properties and behaviors from their base classes. A base class reference can point to objects of the base class or any derived class, allowing the invocation of overridden methods at runtime.


Example of method overriding:


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

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

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

class Program
{
    public static void Main()
    {
        Animal myAnimal = new Dog();
        myAnimal.MakeSound();  // Outputs: The dog barks

        myAnimal = new Cat();
        myAnimal.MakeSound();  // Outputs: The cat meows
    }
}


In this example, we have a base class `Animal` and two derived classes `Dog` and `Cat`. Each derived class overrides the `MakeSound()` method of the base class. By using a reference to the base class, we can switch between different derived class objects and invoke the appropriate `MakeSound()` method at runtime.


Tags

Post a Comment

0Comments

Post a Comment (0)

#buttons=(Accept !) #days=(20)

Our website uses cookies to enhance your experience. Check Now
Accept !