Overloading

Method overloading is when multiple methods have the same name, but different parameters. For example, you might have a Print method that outputs its parameter to the console window:

void Print(int a)
{
Console.WriteLine(“Value: “+a);
}

The + operator is used to concatenate values. In this case, the value of a is joined to the text “Value: “. This method accepts an integer argument only. Overloading it will make it available for other types, such as double:

void Print(double a)
{
Console.WriteLine(“Value: “+a);
}

 

Note:
Now, the same Print method name will work for both integers and doubles.

When overloading methods, the definitions of the methods must differ from each other by the types and/or number of parameters.
When there are overloaded methods, the method called is based on the arguments. An integer argument will call the method implementation that accepts an integer parameter. A double argument will call the implementation that accepts a double parameter. Multiple arguments will call the implementation that accepts the same number of arguments.

The Code:

New Project136.png

The Output of Your Program:

New Project137

You cannot overload method declarations that differ only by return type.
The following declaration results in an error.
int PrintName(int a) { }
float PrintName(int b) { }
double PrintName(int c) { }:

Prev Lesson:                      Next Lesson:

Passing Arguments       Recusion