Tuesday, April 16, 2024 04:16

Table of contents >> Functions > Functions and methods overloading

Functions and methods overloading

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:

The above code would function perfectly, no doubt about it. However, using method overloading, we can do it like this:

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: , , , ,

Leave a Reply

Follow the white rabbit