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.

Object-Oriented Programming

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

using System;

namespace Polymorphism
{
    class Program
    {
        class Car
        {
            public void CarDetail()
            {
                Console.WriteLine("Car Toyota is available");
            }

            public void CarDetail(int priceRange)
            {
                Console.WriteLine("Car lamborghini is available its expensive car");
            }

            public void CarDetail(int priceRange, string colour)
            {
                Console.WriteLine("Car mercedes is available in white color");
            }
        }

        static void Main(string[] args)
        {
            Car cr = new Car();
            cr.CarDetail();
            cr.CarDetail(2200000);
            cr.CarDetail(2200000, "White");
            Console.ReadKey();
        }
    }
}

Output

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