Object-Oriented Programming With C# — Polymorphism With Method Overloading

Why does everything even remotely related to engineering have to reference something in Greek?

  1. Topics of Discussion

1. Topics of Discussion

In this tutorial, we are going to learn about polymorphism with method overloading. So, let’s have some fun.

2. Polymorphism with Method Overloading

Polymorphism is the third of the four OOP principles we are going to discuss. The gist of it is that through polymorphism, you have the possibility of having two or more methods, that have the same name, but perform different actions. It can be obtained through method overloading or method overriding.

In order to understand polymorphism through method overloading, we need to understand the concept of the method signature. The signature of a method contains the following things:

  • the name of the method

In order to implement polymorphism with overloaded methods, you have to do one of the following:

  • change the parameter list of the method

The name of the method of course remains the same. Also worth noting is that changing the return type alone is not enough, because if the parameter list is the same, C# won’t be able to distinguish between them. This is caused by the fact that the return type of a method is not part of the method signature, and as a result, C# would view two methods with the same name and same parameter list as being identical, regardless of the return type.

Here are some polymorphic method examples:

public int Sum(int a, int b)
return a + b;
public int Sum(params int[] numbers)
return numbers.Sum();
public double Sum(double a, double b)
return a + b;

As you can see, the second implementation of the method changes only the parameter list. The params keyword is used to tell C# that you can have a variable number of parameters of type int. Here’s an example of how you can invoke that method:

obj.Sum(1, 2, 3, 4);

Of course, obj is an instance of the class the contains the Sum methods.

Finally, the third implementation of the method changes both the return type and the parameter list.

And that about covers it for this tutorial. In the next one, we are going to talk about how a class can inherit another. See you then.


Microsoft Docs

Tutorials Point

Connect with Upstack for hiring pre-vetted tech talent for your project! Let’s grow together!

Originally published at upstack.co on 4 May 2021, by Andrei Moraru.



The World's Best Developers on Demand

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store