What is run time polymorphism in C#?

CsharpProgrammingServer Side Programming

Runtime polymorphism has method overriding that is also known as dynamic binding or late binding. It is implemented by abstract classes and virtual functions.

Abstract Classes

Abstract classes contain abstract methods, which are implemented by the derived class.

Let us see an example of abstract classes that implements run time polymorphism −

Example

 Live Demo

using System;

namespace PolymorphismApplication {
   abstract class Shape {
      public abstract int area();
   }

   class Rectangle: Shape {
      private int length;
      private int width;

      public Rectangle( int a = 0, int b = 0) {
         length = a;
         width = b;
      }

      public override int area () {
         Console.WriteLine("Rectangle class area :");
            return (width * length);
      }
   }

   class RectangleTester {
      static void Main(string[] args) {
         Rectangle r = new Rectangle(10, 7);
         double a = r.area();
         Console.WriteLine("Area: {0}",a);
         Console.ReadKey();
      }
   }
}

Example

Rectangle class area :
Area: 70

Virtual Functions

When you have a function defined in a class that you want to be implemented in an inherited class(es), you use virtual functions. The virtual functions could be implemented differently in different inherited class and the call to these functions will be decided at runtime.

raja
Published on 08-Aug-2018 07:53:42
Advertisements