C# Polymorphism
Polymorphism is one of the primary pillars of the object-oriented programming language.
- The word polymorphism means having many forms. In OOPs paradigm, polymorphism is often expressed as "One Interface Multiple Functions".
There are two types of polymorphism -
1. Compile Time | Static| Early Binding Polymorphism - is achieved by method overloading and operator overloading. It is also known as static polymorphism.
a. Function/Method overloading - Having two or more methods with same name but different in parameters, is known as method overloading in C#.
The advantage of method overloading is that it increases the readability of the program because you don't need to use different names for same action.
You can perform method overloading in C# by two ways:
- By changing number of arguments
- By changing data type of the arguments
- public class Cal{
- public static int add(int a,int b){
- return a + b;
- }
- public static int add(int a, int b, int c)
- {
- return a + b + c;
- }
- }
b. Operator/Member overloading- If we create two or more members having same name but different in number or type of parameter, it is known as member overloading. In C#, we can overload:
- methods,
- constructors, and
- indexed properties
It is because these members have parameters only.
- public class Cal{
- public static int add(int a, int b){
- return a + b;
- }
- public static float add(float a, float b)
- {
- return a + b;
- }
- }
2. Runtime Time | Dynamic | Late Binding Polymorphism - is achieved by method overriding which is also known as dynamic polymorphism.
a. Virtual/Method Overriding - If derived class defines same method as defined in its base class, it is known as method overriding in C#. It is used to achieve runtime polymorphism. It enables you to provide specific implementation of the method which is already provided by its base class.
To perform method overriding in C#, you need to use virtual keyword with base class method and override keyword with derived class method.
- public class Animal{
- public virtual void eat(){
- Console.WriteLine("Eating...");
- }
- }
- public class Dog: Animal
- {
- public override void eat()
- {
- Console.WriteLine("Eating bread...");
- }
- }
Comments
Post a Comment