Home > C# > Polymorphism in C#

C# Polymorphism

In general, Polymorphism means having more than one shapes or forms. It is one of the main paradigms of Object-oriented programming along with encapsulation and inheritance. In OOP polymorphism is having one interface with many implementations. You can express polymorphism in C# as the ability of different types of objects to present a unique interface for the different implementations of the same function. In c# polymorphism allows us to redefine the functions in the child classes.

In C# polymorphism has two types:

  • 1- Static
  • 2- Dynamic

polymorphism in c#

Static

Static or compile-time polymorphism is achieved by function overloading & operator overloading. Sometimes you may refer it as ad-hoc polymorphism or early binding as well. The compile-time polymorphism as the name suggests the identification of the function call takes place at the time of compiling the program.

In function overloading, a class is having more than one functions in it with the same name but different parameters. In Static polymorphism, the compiler checks the arguments for the function and then decides the suitable function for calling at the compile time. This will give us an error if we don’t have the function definition matching with the function call.

Static Polymorphism in C# Code Example

using System;
namespace polymorphism
{
     class Program
     {
          public void sum(int a, int b)
          {
               Console.WriteLine( "Sum of Integers:"+ a+" & " + b +"= "+(a + b));
          }
          public void sum(Double a, Double b)
          {
               Console.WriteLine("Sum of Doubles:" + a + " & " + b + "= " + (a + b));
          }
          static void Main(string[] args)
          {
               Program p = new Program();
               p.sum(10,20);
               p.sum(15.6,13.2);
          }
     }
}

static C# polymorphism

 

 

 

 

Now as in the above example we have two functions with the same name as the sum with each having its own definition.

What if we make a call to the function which doesn’t have the definition in the class? Let’s have a look at that

using System;
namespace polymorphism
{
     class Program
     {
          public void sum(int a, int b)
          {
               Console.WriteLine( "Sum of Integers:"+ a+" & " + b +"= "+(a + b));
          }
          public void sum(Double a, Double b)
          {
               Console.WriteLine("Sum of Doubles:" + a + " & " + b + "= " + (a + b));
          }
          static void Main(string[] args)
          {
               Program p = new Program();
               p.sum(10,20);
               p.sum(15.6,13.2);
               p.sum("Hello","World");
          }
     }
}

static polymorphism error

 

 

 

 

 

 

As it is the compile-time polymorphism, so it gives us an error while compiling the program.

Dynamic

In c# you can achieve dynamic or runtime polymorphism by the use of inheritance & virtual functions i.e. function overriding. In runtime polymorphism the identification of object for the overridden method call is done at runtime. Sometimes we may refer to Runtime polymorphism as inclusion or subtyping polymorphism or late binding.

Function overriding is the concept in which both the parent class and the child class have the same function of their own. It differs from function overloading in a way that both the functions in the classes have the same name and same parameters as well. In runtime polymorphism, we can point to the child class from the object of the parent class at runtime. This refers to the late binding.

As we refer the child class object to the parent class, so the function call depends on the object we refer to the base class. In this case, the compiler doesn’t know that whether the function is available for overriding or not. Hence, no compile time error will occur. Though at the runtime if no function is available it will generate the error.

Dynamic Polymorphism in C# Code Example

using System;
namespace polymorphism
{
     class Program
     {
          public class parent
          {
               public virtual void display()
               {
                    Console.WriteLine("Parent class Display Function.");
               }
          }
          public class child:parent
          {
               public override void display()
               {
                    Console.WriteLine("Child class Display Function.");
               }

          }
          static void Main(string[] args)
          {
               //parent class object refering to parent class
               parent p1 = new parent();
               p1.display();
               //parent class object refering to child class
               parent p2 = new child();
               p2.display();
          }
     }
}

dynamic polymorphism in c#

 

 

 

 

Now, what if we don’t have the function definition available in the child class? In that case, the object will point to parent class function. And make its call. Have a look at it.

using System;
namespace polymorphism
{
     class Program
     {
          public class parent
          {
               public virtual void display()
               {
                    Console.WriteLine("Parent class Display Function.");
               }
          }
          public class child:parent
          {
          }
          static void Main(string[] args)
          {
               //parent class object refering to parent class
               parent p1 = new parent();
               p1.display();
               //parent class object refering to child class
               parent p2 = new child();
               p2.display();
          }
     }
}

dynamic polymorphism in c#

 

 

 

 

Why use virtual keyword in runtime polymorphism?

According to MSDN, “The virtual keyword is used to modify a method, property, indexer or event declaration, and allow it to be overridden in a derived class.”

It is necessary to use virtual keyword in the base class function so that we can override it in the child class. Virtual keyword makes the function virtual. A virtual function is the one whose behavior can change in the child class.

We can achieve runtime polymorphism in c# by using abstract classes.

There are some rules for an abstract class.

  • 1- You cannot instantiate an abstract class.
  • 2- You cannot declare an abstract function outside the abstract class.
  • 3- An Abstract class cannot be sealed.

Have a look at this below example of runtime polymorphism in c# using the abstract class.

using System;
namespace polymorphism
{
    class Program
    {
        public abstract class shape
        {
            public abstract void calculate_area();
        }
        public class Circle: shape
        {
            double radius;
            public Circle()
            {
                radius = 0;
            }
            public Circle(double r)
            {
                radius = r;
            }
            public override  void calculate_area()
            {
                double pi = 3.14;
                Console.WriteLine("Area of circle = "+ (pi*radius*radius));
            }
        }
        public class Rectangle : shape
        {
            double length;
            double width;
            public Rectangle()
            {
                length = 0;
                width = 0;
            }
            public Rectangle(double l, double w)
            {
                length = l;
                width = w;
            }
            public override void calculate_area()
            {
                Console.WriteLine("Area of Rectangle = " + (length *width));
            }
        }
        public class Square : shape
        {
            double side;
            public Square()
            {
                side = 0;
            }
            public Square(double s)
            {
                side = s;
            }
            public override void calculate_area()
            {
                Console.WriteLine("Area of Rectangle = " + (side * side));
            }
        }
        static void Main(string[] args)
        {
            Square s = new Square(3.6);
            s.calculate_area();
            Rectangle r = new Rectangle(5.3, 4.6);
            r.calculate_area();
            Circle c = new Circle(5.0);
            c.calculate_area();
        }
    }
}

untime polymorphism using abstract class

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.