Understanding polymorphism

Polymorphism is a Greek word whose literal translation to English is many-shaped. In programming terms, it's referred to as one interface with multiple functions. Let's try to understand polymorphism by looking at the following diagram:

 

In the preceding diagram, we have some program code that runs on Input 1 and gives Output 1. Now, let's say we make a mistake and send an incorrect input of Input 2 instead. In this case, unfortunately, the program code may error out and send an error message. In such a scenario, we can use polymorphism. With polymorphism, the same example will be represented as follows:

As we can see, by using polymorphism, we will maintain three copies of the code in memory and depending on the type of input received, the appropriate copy of the program code will be loaded and executed. 

There are two types of polymorphism possible in C#:

  • Static/compile-time polymorphism, that is, method overloading or function overloading
  • Execution time polymorphism, that is, method overriding or virtual functions

Let's go through each of these types and use code examples to understand how they work.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.191.62.122