Polymorphism in C#

Polymorphism :Polymorphism divided two parts ploy means multiple and morph means forms .So

Polymorphism means many forms. Here in c# it means one name many forms. Essentially it capability of one object to behave in multiple ways. It achieved in c# two ways.

Types of polymorphism

 

  • Compile time polymorphism (static binding)
  • Run time polymorphism (dynamic binding)

 

Compile time polymorphism

Compile time polymorphism is achieved in C# using concept of overloading. As we know, with overloading, multiple methods with same name are created. However the parameters on each method vary.

Example

  1. Using System;  
  2. Public class myclass  
  3. {  
  4.     Public int sum(int A, int B)  
  5.     {  
  6.         Return A + B;  
  7.     }  
  8.     Public float Sum(int A, float B)  
  9.     {  
  10.         Return A + B;  
  11.     }  
  12.   
  13. }  
The above example Sum method used with different parameters. First it taken int A , int B and in the second method it taken int A,float B. So it is a perfect example of overloading in c #.

Runtime Polymorphism

Runtime polymorphism is also called as Dynamic polymorphism. This type of polymorphism achieved in c# using overridden concept. Overridden means same and same parameter or signature but different in the implementation. During run time method overriding can be achieved by using inheritance principle and using “Virtual” and “Override” keyword. So this type of polymorphism can also be called as late binding.

Example of runtime polymorphism

  1. Using system;  
  2. Class maruthi  
  3. {  
  4.     Public virtual void Display()  
  5.     {  
  6.         Console.writeline(“maruthi car”);  
  7.     }  
  8. }  
  9. Class Esteem: Maruthi  
  10. {  
  11.     Public override void Display()  
  12.     {  
  13.         Console.writeline(“Maruthi esteem”);  
  14.     }  
  15. }  
  16. class testcall  
  17. {  
  18.     Public static void Main()  
  19.     {  
  20.         Maruthi m = new Maruthi();  
  21.         m = new Esteem();  
  22.         m.Display();  
  23.     }  
  24. }