C# Method Overloading

1.Basics

Method overloading (also called Ad-hoc Polymorphism) consists in creating multiple functions with the same name but that have different headers. The methods can be differentiated by their parameters’ type/number. We say that method a() is different from a(int x) and also a(int x) is different from a(float x).
So, you can have multiple methods with the same name but with different parameters – that’s basically method overloading.

2.Implementing Method Overloading

In this tutorial I’ll create a simple class that contains 2 methods. Those will return the sum of 2 numbers – numbers are transmitted as parameters.
I’ll put everything in a class called math, to make it easier to understand.

Because of method overloading we can call the method without involving other instructions/conditions. In this case sum() has 2 overloads, because there are other 2 methods with the same name.
Our program will know what to choose, according to the parameters provided when the method is called.
 

3.Calling the Overloadable Method


How can this help me?

It might not look useful, but it improves a lot your project’s structure:
– imagine having methods with different names but which do the same thing, only because you must give them different parameters
It keeps your sourcecode ‘clean’ and makes it easier to understand and also easier to work with (for you and/or your teammates).
Previous
Next Post »