Method Overloading
Method overloading allows you to declare two methods with the same name but has different signatures or parameter set. The program will automatically detect which method you are calling by looking at the arguments you are passing to the method. The signature of a method shows the order and type of each parameter. Let’s take a look at the method below:
void MyMethod(int x, double y, string z)
would have a signature of
MyMethod(int, double, string)
Note that the return type and the names of the parameter are not included in the signature of the method.
The example below demonstrates method overloading.
using System;
namespace MethodOverloadingDemo
{
public class Program
{
static void ShowMessage(double number)
{
Console.WriteLine("Double version of the method was called.");
}
static void ShowMessage(int number)
{
Console.WriteLine("Integer version of the method was called.");
}
static void Main()
{
ShowMessage(9.99);
ShowMessage(9);
}
}
}
Example 1 – Method Overloading Demo
Double version of the method was called. Integer version of the method was called.
The program defined two methods with similar names. If method overloading is not supported by C#, then the program will have a hard time choosing which method to use when the name of the method is called. The secret is in the types of the parameters of a method. The compiler can differ two or more methods if they have a different set of parameters. When we called the method, it reads the type of the argument. On the first call (line 19), we passed a double value so the ShowMessage() (line 7-10) with double as the parameter was executed. On the second method call (line 20), we passed an int argument so the other ShowMessage() (line 12-15) with int as the argument was executed. It’s essential to know method overloading.
The big purpose of method overloading is when multiple methods do the same task but only matters on the data that they require. A lot of methods in .NET Classes are overloaded. For example, the Console.WriteLine() method has multiple overloads. You saw that it can accept one string argument which is the string to display, and another version of it accepts 2 or more arguments, the first being the format string.