What is polymorphism in C# ?

CsharpProgrammingServer Side Programming

Polymorphism can be static or dynamic. In static polymorphism, the response to a function is determined at the compile time. In dynamic polymorphism, it is decided at run-time.

In static polymorphism, the response to a function is determined at the compile time. In dynamic polymorphism, it is decided at run-time. Dynamic polymorphism is what we call late binding.

Compile Time Polymorphism or Static Binding

The mechanism of linking a function with an object during compile time is called early binding. It is also called static binding.

Run Time Polymorphism or Dynamic Binding

Runtime polymorphism has method overriding that is also known as dynamic binding or late binding.

Let us see an example of compile time polymorphism that implement method overloading −

Example

 Live Demo

using System;

namespace PolymorphismApplication {
   class Printdata {
      void print(int i) {
         Console.WriteLine("Printing int: {0}", i );
      }

      void print(double f) {
         Console.WriteLine("Printing float: {0}" , f);
      }

      void print(string s) {
         Console.WriteLine("Printing string: {0}", s);
      }

      static void Main(string[] args) {
         Printdata p = new Printdata();

         // Call print to print integer
         p.print(5);

         // Call print to print float
         p.print(500.263);

         // Call print to print string
         p.print("Hello C++");
         Console.ReadKey();
      }
   }
}

Output

Printing int: 5
Printing float: 500.263
Printing string: Hello C++
raja
Published on 08-Aug-2018 09:05:53
Advertisements