Polymorphism in C-sharp

Polymorphism in C# is one of the most important concepts of OOPs. Polymorphism is the concept in which actions are performed depending upon the current situations. The word polymorphism is a Greek word which means the ability to take more than one form. Polymorphism helps to minimize the complexity of the program.

ploymorphism in C#Image Source: c-sharpcorner.com

Types of Polymorphism:

Polymorphism in C# has following forms:

1. Static Polymorphism:

Static polymorphism is done at compile time of the program. This means the actions to be taken are decided at the time of program compilation. It is also known as ‘Compile time polymorphism’ or ‘Early binding’. Static polymorphism in C# is implemented in the form of method overloading and operator overloading.

a. Method Overloading:

Function overloading is the process of making multiple methods with same name and different parameter list. It is mandatory that overloaded methods have a different number of parameters and/or different types of parameters.

It is the process of writing different versions of the method which behaves differently depending upon the parameters passed in the method call.

The compiler checks the parameters and decides that which method is going to be executed at the compile time. The overloaded methods may have different return types.

It is the process of writing different versions of the method which behaves differently depending upon the parameters passed in the method call.

The overloaded methods may have different return types.

Example:

using System;
namespace MethodOverloadingDemo
{
     class AdditionDemo
    {
        public void Add(int a,int b)
         {
             Console.WriteLine("Addition of A and B is: {0}",a+b);
         }
         public void Add(int a, int b,int C)
         {
             Console.WriteLine("Addition of A, B and C is: {0}", a + b+C);
         }
         public void Add(string a, string b)
         {
              Console.WriteLine("Concatenation of string A and B is: {0}", a + b);
         }
     }
     class Program
     {
          static void Main(string[] args)
         {
              AdditionDemo demo1 = new AdditionDemo();
              demo1.Add(1, 2);
              demo1.Add(10, 10, 10);
              demo1.Add("It is ", "C# programming.");
              Console.ReadLine();
          }
       }
}

The output of above program is

Addition of A and B is: 3
Addition of A, B and C is: 30
Concatenation of string A and B is: It is C# programming.
Recommended Post   C# programming language

b. Operator Overloading:

Operator overloading is the concept of defining the meaning of operator relative to specific user-defined class. In simple words, it is the process to change the default behavior of operator for user defined classes.

With the help of operator overloading, we can add different behaviors to the operator for different classes. Suppose a plus operator (+) which adds two numbers in arithmetic operations, but in our user defined class we want to use plus operator to add two character class members to form a string result, we can achieve this with the help of operator overloading.

With the help of operator overloading, we can add different behaviors to the operator for different classes. Suppose a plus operator (+) which adds two numbers in arithmetic operations, but in our user defined class we want to use plus operator to add two character class members to form a string result, we can achieve this with the help of operator overloading.

Following operators support overloading in C#:

Operator Type Operators

Arithmetic Operators +, – ,*, /, %, ++, —

Relational Operators ==, !=, >, <, >=, <=

Bitwise Operators |, &, ^, >>, <<, ~, !

Following operators does not support overloading in C#:

Operator Type Operators

Logical Operators ||, &&,

Assignment Operators =, +=, -=, *=, /=, %=

Other Operators ., (), ?:, sizeof()

Defining operator method:

The operator method defines the task to be done by the overloaded operator relative to class in which method is defined. This operator method must be static and public.

The syntax for unary operator method is as below:

public static <return_type> operator <op> (Type t)
{
    //Task statements to be executed by operator
}

In unary operator overloading, operator method takes only one argument which is of type class in which operator method is defined. The method must have ‘operator’ keyword preceded by the actual operator sign.

Recommended Post   C# Tutorial

Example:

using System;
namespace UnaryOperatorOverloadingDemo
{
class UnaryDemo
{
     public char Ch;
     public static string operator +(UnaryDemo UD)
     {
          string result = UD.Ch.ToString() + UD.Ch.ToString();
          return result;
     }
}
class Program
{
     static void Main(string[] args)
     {
          UnaryDemo unaryDemo = new UnaryDemo();
          unaryDemo.Ch = 'A';
          string s = +unaryDemo;
          Console.WriteLine("The result of plus operation is {0}",s);
          Console.ReadLine();
      }
  }
}

The output of above program is

The result of plus operator is AA

The syntax for binary operator method is as below:

public static <return_type> operator <op> (Type t1, Type t2)
{
   //Task statements to be executed by operator
}

In binary operator overloading, the operator method takes two arguments argument from which at least one is of the type in which operator method is defined. The method must have ‘operator’ keyword preceded by the actual operator sign.

Example:

using System;
namespace BinaryOperatorOverloadingDemo
{
class Program
{
     class BinaryDemo
     {
          public char Ch;
          public static string operator +(BinaryDemo BD1, BinaryDemo BD2)
          {
              string result = BD1.Ch.ToString() + BD2.Ch.ToString();
              return result;
          }
      }
      static void Main(string[] args)
      {
          BinaryDemo binaryDemo1 = new BinaryDemo();
          binaryDemo1.Ch = 'A';
          BinaryDemo binaryDemo2 = new BinaryDemo();
          binaryDemo2.Ch = 'B';
          string result = binaryDemo1 + binaryDemo2;
          Console.WriteLine("The result of plus operator is {0}", result);
          Console.ReadLine();
       }
}
}

The output of above program is

The result of plus operator is AB

Note: In the case of relational operators, you should overload operators in the pair. Means if you want to overload == operator then it is necessary to overload != operator also.

2. Dynamic Polymorphism:

Dynamic polymorphism in C# is done at programs runtime. That means the actions to be taken or the program behavior is decided at the runtime.

It is also known as ‘Runtime Polymorphism’ or ‘Early binding’. In C# dynamic polymorphism is achieved by method overriding.

Recommended Post   C# Language Fundamentals

Method Overriding:

Method overriding happens in inheritance where the base and derived class relationship exists. In method overriding the method implementation of the method in the base class is changed in derived class. It is nothing but the writing the same method (with the same name and argument list) in derived class but with different execution task.

In this process, the method in the base class is declared as ‘virtual method’. The virtual keyword uses to tell the compiler that the method may be redefined in derived classes.

The virtual methods cannot be declared as static or abstract. To override these virtual methods in derived classes ‘override’ keyword is used.

Method overriding achieves the C# most powerful concept known as ‘dynamic method dispatch’. In this mechanism call to overridden method is resolved at runtime. This is how C# implements dynamic polymorphism.

Example:

using System;
namespace MethodOverridingDemo
{
    class Program
    {
        class BaseClass
        {
             public virtual void Show()
             {
                 Console.WriteLine("This is Base class version of Show() Mehtod.");
             }
         }
     class DerivedClass1 : BaseClass
     {
          public override void Show()
          {
              Console.WriteLine("This is Derived class 1 version of Show() Mehtod.");
          }
      }
      class DerivedClass2 : BaseClass
      {
          public override void Show()
          {
              Console.WriteLine("This is Derived class 2 version of Show() Mehtod.");
          }
      }
      static void Main(string[] args)
      {
           BaseClass DC1 = new DerivedClass1();
           DC1.Show();
           BaseClass DC2 = new DerivedClass2();
           DC2.Show();
           Console.ReadLine();
        }
 }
}

The output of above program is

This is Derived class 1 version of Show() Mehtod.
This is Derived class 2 version of Show() Mehtod.
Content Protection by DMCA.com