Learn Object Oriented Programming Using C#: Part 7

Before reading this article, please go through the following articles:
  1. Object-Oriented Programming Using C#: Part 1
  2. Object-Oriented Programming Using C#: Part 2
  3. Object-Oriented Programming Using C#: Part 3
  4. Object-Oriented Programming Using C#: Part 4
  5. Object-Oriented Programming Using C#: Part 5
  6. Learn Object-Oriented Programming Using C#: Part 6

Polymorphism

 
How often do we use polymorphism in our programs? Polymorphism is the third main pillar of Object-Oriented Programming languages and we use it nearly daily without thinking about it.
 
Here is a very simple diagram that will explain the polymorphism itself.
 
Learn-OOP-in-C-Sharp.jpg
 
In simple words, we can say that whenever we are overloading the methods of a class it is called polymorphism. Or you can say polymorphism is often expressed as "one interface, multiple functions". This means we have more than one function with the same name but different parameters.
 
Example
  1. using System;  
  2. namespace Polymorphism  
  3. {  
  4.     class Program  
  5.     {  
  6.         class car  
  7.         {  
  8.             public  void CarDetail()  
  9.             {  
  10.                 Console.WriteLine("Car Toyota is available");  
  11.             }  
  12.    
  13.             public void CarDetail(int priceRange)  
  14.             {  
  15.                 Console.WriteLine("Car lamborghini is available its expensive car");  
  16.             }  
  17.    
  18.             public void CarDetail(int priceRange, string colour)  
  19.             {  
  20.                 Console.WriteLine("Car mercedes is available in white color");  
  21.             }  
  22.         }  
  23.         static void Main(string[] args)  
  24.         {  
  25.             car cr = new car();  
  26.             cr.CarDetail();  
  27.             cr.CarDetail(2200000);  
  28.             cr.CarDetail(2200000, "White");  
  29.             Console.ReadKey();  
  30.         }  
  31.     }  

Learn-Polymorphism-in-C-Sharp.jpg
 
In this example, we have created three different functions with the same name (CarDetail) having a different set of parameters. In the next topic I will discuss Polymorphism in more detail with its two types:
  1. Static Polymorphism
  2. Dynamic Polymorphism