Saturday, May 13, 2023

Polymorphism in C#| polymorphism| Types of polymorphism in c#

 What is polymorphism in c#?


Polymorphism is a fundamental concept in object-oriented programming (OOP) and is fully supported in C#. Polymorphism allows objects to take on multiple forms, depending on the context in which they are used.


There are two main types of polymorphism in C#:


1. Compile-time polymorphism: This is also known as method overloading. Method overloading allows multiple methods with the same name to be defined in a class, but with different parameter lists. The compiler determines which method to call based on the number and types of arguments passed to it. For example:



class MathOperations

{

    public int Add(int a, int b)

    {

        return a + b;

    }


    public double Add(double a, double b)

    {

        return a + b;

    }

}



In this example, the "MathOperations" class defines two methods with the same name "Add", but with different parameter types (integers and doubles). When the "Add" method is called, the compiler chooses the appropriate method based on the arguments passed.


2. Runtime polymorphism: This is also known as method overriding. Method overriding allows a derived class to provide its own implementation of a method that is already defined in the base class. The derived class can provide its own implementation of the method by using the "override" keyword. For example:



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");

    }

}



In this example, the "Animal" class defines a virtual method "MakeSound", which can be overridden by the "Dog" class. The "Dog" class provides its own implementation of the "MakeSound" method using the "override" keyword.


Now, we can create an object of the "Dog" class and call its "MakeSound" method. At runtime, the overridden method in the derived class is called:



Dog dog = new Dog();

dog.MakeSound(); // outputs "The dog barks"



In summary, polymorphism is a powerful mechanism in C# that allows objects to take on multiple forms. Compile-time polymorphism is achieved through method overloading, while runtime polymorphism is achieved through method overriding. Both types of polymorphism allow for more flexible and extensible code.

No comments:

Post a Comment

If you have any query kindly let me know.

Blazor drawback| drawback of blazor| Disadvantage of blazor in c#

  Blazor drawback| drawback of blazor| Disadvantage of blazor in c# While Blazor offers many advantages, it also has a few drawbacks to cons...