Polymorphism implementation in C#

 In object-oriented programming, Polymorphism is the ability of an object to take on many forms. It allows us to perform a single action in different ways.

In C#, Polymorphism is an ability to process objects differently depending on their data type or class. More specifically, it's the flexibility to redefine methods for derived classes.


Why Polymorphism is needed?


Polymorphism helps us to reuse the code, that is once written, to be tested and implemented. It also helps us to achieve abstraction in our application code, which increases our code reusability and readability.


Types of  Polymorphism

There are two types of polymorphism:
  1.  Static (Compile-time) polymorphism.
  2.  Dynamic (Run-time) polymorphism.

Static Polymorphism

Static polymorphism is a polymorphism that occurs at compile time, in which the linking of a method with an object is resolved at compile time.

 In C#,  Method and operator overloading are an example of static polymorphism.

Let's take an example to implement this in C#:

In the preceding example, we have defined two methods with the same name Add() but with different input parameter types.

Dynamic Polymorphism

Dynamic polymorphism is a polymorphism that occurs during the application execution, in which the linking of a method with an object is resolved just before that method execution (While invoking that method). The method overriding is an example of dynamic polymorphism. Here, a call to an overridden method is resolved at runtime. It allows us to redefine a method to provide its new definition.

 In C#, dynamic polymorphism is accomplished by using abstract and virtual methods.

Let's take an example to implement this in C#:


In the preceding example, the response of the VehicleType() method will be determined at run-time based on the overridden version of it.

Vikash Chauhan

C# & .NET experienced Software Engineer with a demonstrated history of working in the computer software industry.

Post a Comment

Previous Post Next Post

Contact Form