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.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
|
class math
{
//take a look at the methods below - all are different methods
//but they have the same name
public int sum(int a, int b) // 2 parameters, both are 'int'
{
return a + b;
}
public int sum(float a, float b) // 2 parameters, but they're 'float'
{
return (int)(a + b);
}
public int sum(int a, int b, int c) // 3 parameters, all of them are 'int'
{
return a + b + c;
}
}
|
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
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
math m = new math();
Console.WriteLine(m.sum(2,3));
//calls the first method in the class because
//both parameters are 'int'
Console.WriteLine(m.sum(3.5f, 4.5f));
//this calls the second method because
//the parameters are float
Console.WriteLine(m.sum(3,4,5));
//and this calls the third method because
//there are 3 parameters
|
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).
Sign up here with your email
ConversionConversion EmoticonEmoticon