Polymorphism in C#

 

Polymorphism is an approach which tells the program whenever the input changes the output/behaviour also changes accordingly to it. Polymorphism can be implemented in three different ways. Those are Overloading, Overriding and Hiding. 

Overloading:Overloading is again divided into three different types and those are Method Overloading, Constructor Overloading and Operator Overloading. 

Method Overloading: It is an approach of defining multiple methods in a class with the same name by changing their signatures. Changing the signature means changing the number of input parameter or changing the order of the parameters or changing the data type of parameter which are passed to the method. 

Eg: 

        public void EmployeeInfo(); 

        public void EmployeeInfo(int Id); 

        public void EmployeeInfo(int Id, string Name); 

        public void EmployeeInfo( string Name, int Id);     

Change in the return type of a method will not be taken into consideration in case of overloading. Method overloading is an approach that allows you to define multiple behaviours to a method. 

Constructor Overloading: Constructor overloading is also like method overloading, where constructors of the class will overload. That means we can define multiple constructors with different signatures. If a class contains multiple constructors, we can create object by using any of the constructor. 

class Employee 

{ 

        Employee() 

        {        

 

        }

 

        Employee(int Id) 

        {

 

        }

 

        Employee(int Id, string Name) 

        { 

 

        }

}

 

As shown above we have three different contructors for Employee class with different signatures. Constructors are overloadded in a class either to initialize the variables with default values or to initialize the variables with user defined values. 

Inheritance based Overloading: We can overload the methods within any class as well as a class methods can be overloaded under a child class also. If at all the methods of a class are overloaded under its child class we can call it as inheritance based overloading.

 

Method Overriding:If at all a parent class method is reimplemented under child class with the same signature then it is called Method Overridinng. For example if parent class has EmployeeInfo(int Id) method and if child class also has same EmployeeInfo(int Id) method then it is called Method Overriding.