There are times when we have functions or methods that perform basically the same thing, but use different kind of parameters. So, in other words, there are cases when we have methods with the same name, but with different signatures. What does that mean? It means we can have a few methods with the same name, but with different type of parameters, different arrangement of parameters, or different number of parameters. We call these variations overloads of the method/function (or method/function overloading).
For example, lets consider we want to have some functions that would display on the console different kinds of types: strings, numbers, floats, whatever. We can do it like this:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
static void Main(string[] args) { DisplayString("hello"); DisplayInt(1); DisplayDecimal(3.1m); Console.Read(); } static void DisplayString(string myString) { //display string } static void DisplayInt(int myInt) { //display int } static void DisplayDecimal(decimal myDecimal) { //display decimal } |
The above code would function perfectly, no doubt about it. However, using method overloading, we can do it like this:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
static void Main(string[] args) { Display("hello"); Display(1); Display(3.1m); Console.Read(); } static void Display(string myString) { //display string } static void Display(int myInt) { //display int } static void Display(decimal myDecimal) { //display decimal } |
You can notice that we have three methods with the same name, Display(). How is it possible? Shouldn’t the compiler complain about a name of the method already existing? Well, no, not in this case, because the signatures of our methods are different, meaning, we have different types of parameters declared in each method.
When we call our Display() method with different parameters – int, string, etc, the compiler automatically detects the type used as a parameter call, and selects the appropriate overload of our method.
The following image shows the 8th overload of the method WriteLine(), for writing an integer number on the console. The method WriteLine() has 19 overloads.
The concepts explained in this lesson are also shown visually as part of the following video:
Tags: functions, functions parameters, methods, methods parameters, overloading