Method Overloading in Programming

This post refers to the previous one we saw about polymorphism because in that post we discussed what is known as static polymorphism.

We can define method overloading as polymorphism at runtime.

 

1 - What is method overloading?

Method overloading means that we have multiple methods within a class that have the same name but different parameters.

These parameters can differ in several aspects:

  1. Number of parameters
  2. Type of parameters
  3. Order of parameters

Keep in mind that we cannot define two identical methods, meaning with the same name, same parameters and the same order, as this would result in a compilation error.

 

 

2 - Method overloading example in C#

The simplest way to see this is with an example.

We have a class that performs a sum where we pass two values.

public int Sum(int item1, int item2){    return item1 + item2;}

Now, what we want is to send 3 parameters instead of 2. What we would do, instead of changing the names (which would be a bad practice), is create another method with the same name, but pass three parameters instead of two.

public int Sum(int item1, int item2){    return item1 + item2;}public int Sum(int item1, int item2, int item3){    return item1 + item2 + item3;}

And as I mentioned previously, we can also have the same number of parameters but with different types; the compiler knows which method to use and no problem occurs.

public int Sum(int item1, int item2){    return item1 + item2;}public string Sum(string item1, int item2){    return $"{item2} added to {item1}";}

As we see, when executing the code, it works without any problems. Moreover, when we are writing the method we want to use, Visual Studio detects the overloading and does not show us several methods to choose from. Instead, it shows us only one and indicates that there are 2 more methods that are overloaded.

method overloading oop

After selecting the method, we can iterate through the different overloads using the up and down keys.

overloading oop

And this would be an example of calling both methods, and it works without any issue

int sumResult1 = exampleOverload.Sum(1, 2);int sumResult2 = exampleOverload.Sum(1, 2, 3);

This is how we implement method overloading in C#, defining multiple methods with the same name but different parameters depending on the requirements.

The code we used in this course is available on Github at the following link: github link

This post was translated from Spanish. You can see the original one here.
If there is any problem you can add a comment bellow or contact me in the website's contact form

© copyright 2025 NetMentor | Todos los derechos reservados | RSS Feed

Buy me a coffee Invitame a un café