C# Polymorphism with Examples

Learn via video courses
Topics Covered

Overview

Polymorphism in C# is a fundamental concept in Object-Oriented Programming (OOP) that empowers developers to utilize methods with the same name in diverse forms. This article thoroughly covers the fundamentals of polymorphism and its importance in C# programming.

By exploring practical examples, we demonstrate how to implement polymorphism in C# through method overloading and method overriding. The article emphasizes the benefits of polymorphism, such as code reusability and adaptability to different data types and classes. Whether you're a novice or an experienced C# developer, this tutorial serves as a valuable guide in understanding and harnessing the power of polymorphism.

What is Polymorphism in C#?

Polymorphism in C# can be understood as the coexistence of multiple forms or shapes. One interface and several functions is a common way to describe polymorphism in the object-oriented programming paradigm. Polymorphism in C# is an object-oriented programming concept that allows a single interface, such as a method or property, to take on multiple forms. Polymorphism allows for the treatment of objects from different classes as if they belong to a shared base class.

Two primary forms of polymorphism exist compile-time polymorphism, achieved through method overloading, and run-time polymorphism, achieved through method overriding. Polymorphism in C# enhances code flexibility and reusability, allowing developers to write cleaner.

Example:

Output:

In the above example, we have created a class MathOperations inside which we have two methods of the same name, Add().

Here, one of the Add() methods takes no parameters and displays "Add method without arguments.". While the other Add() method takes two parameters and displays " Sum of 5 and 10 is 15".

Hence, the Add() method behaves differently in different scenarios. Or, we can say Add() is polymorphic.

Types of Polymorphism in C#

There are two main types of polymorphism in C#.

  • Compile-Time Polymorphism (Static Polymorphism)
  • Run-Time Polymorphism (Dynamic Polymorphism)

Compile-Time Polymorphism (Static Polymorphism)

Static polymorphism, also known as compile-time polymorphism or early binding, is a concept in object-oriented programming where the method or function to be executed is determined at compile-time rather than runtime. This means that the decision of which method or function to call is made by the compiler based on the data types involved, and it is fixed during the compilation process.

There are two main mechanisms to achieve static polymorphism:

  • Method Overloading
  • Operator Overloading

Method Overloading

Method overloading in C# is a feature that allows you to define multiple methods with the same name in the same class but with different parameters. This enables you to provide different ways of invoking a method based on the number or types of arguments passed to it. The C# compiler uses the method's signature (method name and parameter types) to distinguish between different overloaded methods during compilation.

Example of method overloading in C#:

Output

In the above example, we have overloaded the AddMethod() method:

  • The first AddMethod() method takes two integer parameters and calculates their sum.
  • The second AddMethod() method takes three integer parameters and calculates their sum.
  • The third AddMethod() method takes two double parameters and calculates their sum.

The corresponding method is called based on the number of parameters or data type of parameters given during the method call.

  • math.AddMethod(1, 2) - calls the method with two int parameters, and we will get the output sum of the two integer value : 3.
  • math.AddMethod(1, 2, 3) - calls the method with three int parameters, and we will get the output sum of the three integer values: 6.
  • math.AddMethod(3.14, 2.71) - calls the method with two double parameters, and we will get the output sum of the two double value: 5.85.

Operator Overloading

Operator overloading in C# allows you to define custom behaviors for operators when used with user-defined classes or structs. This enables you to use operators such as +, -, *, /, etc., with your types, providing a natural and intuitive way to perform operations on objects of your class. Operator overloading is a form of static polymorphism, as the resolution of the operator usage occurs at compile time.

In C# to overload an operator, you need to provide a special method in your class or struct that corresponds to the operator you want to overload. The methods used for operator overloading have specific names, and the name of the method depends on the operator you wish to overload.

Example of operator overloading in C#:

Output

As you can see, we've successfully overloaded the + operator for the Point2D class, allowing us to add two Point2D objects together naturally and intuitively.

The compiler automatically recognizes the usage of the + operator with Point2D objects and calls the appropriate overloaded method to perform the addition.

Runtime Polymorphism (Dynamic Polymorphism)

Runtime polymorphism, also known as dynamic polymorphism or late binding, is a concept in object-oriented programming where the method or function to be executed is determined at runtime rather than at compile-time. This allows different objects to exhibit different behaviors for the same method name based on their actual type or class hierarchy.

Runtime polymorphism in C# is typically achieved through inheritance and virtual functions (also known as virtual methods) in object-oriented languages.

The runtime polymorphism is achieved by:

  • Method Overriding

Method Overriding

A derived class may offer a specific implementation for a method that is already declared in its base class by using the C# feature known as method overriding. By overriding a method, the derived class can provide its von of the method, which will be called instead of the base class's version when the method is invoked on an instance of the derived class.

In C# to override a method, the method in the base class must be marked with the virtual keyword, and the method in the derived class must be marked with the override keyword. Additionally, the method signature (name, return type, and parameters) in the derived class must exactly match the method signature in the base class.

Example of method overriding in C#:

Output:

In the above example, we have created a superclass: Shape, and a subclass: Circle.

You'll see that we've used the terms virtual and override in conjunction with methods from the base class and derived classes, respectively. Here,

  • virtual - enables the derived class to override the method.
  • Override - the word "override" denotes that a method is replacing one from the base class.

This is how method overriding in C# is accomplished.

Why Use Polymorphism in C#?

  • Polymorphism in C# allows objects of different types to be treated uniformly, simplifying code, promoting flexibility, and enabling efficient use of inheritance.
  • It enhances code readability and maintainability, enabling developers to create more extensible and adaptable software.
  • Polymorphism allows us to create consistent code. To render a circle in the previous example, we may alternatively build a different function called DrawCircle().
  • This will function flawlessly. We must develop unique methods for every shape, though. As a result, our code will become erratic.
  • To fix this, we can use polymorphism in C# allow to construct a single function called Draw() that will respond differently depending on the shape.

FAQs

Q1. What is polymorphism in C#? A. Polymorphism in C# enables dynamic behavior and code reuse by allowing objects of various kinds to be considered as objects of a common base type.

Q2. How is polymorphism achieved in C#? A. Polymorphism is achieved through inheritance and virtual/override methods.

Q3. What are the benefits of using polymorphism in C#? A. Polymorphism promotes code reusability, extensibility, and flexibility, leading to cleaner and maintainable object-oriented designs.

Conclusion

  • In this article, we learned about Polymorphism in C#, which is the ability of a single method or property to take on multiple forms.
  • The main points covered in this article are:
    • Compile-Time Polymorphism (Static Polymorphism)
    • Run-Time Polymorphism (Dynamic Polymorphism)
    • Benefits of Polymorphism in C#.
  • Polymorphism in C# empowers developers to write flexible and reusable code by allowing objects of different types to be treated uniformly through base classes or interfaces.
  • By using inheritance and overriding methods, C# developers can create dynamic and extensible systems, making it easier to adapt to changing requirements.
  • Embracing polymorphism in C# fosters better software design, encapsulation, and abstraction, leading to maintainable and scalable applications.