C#-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:
Example:
void Print(int a)
{
Console.WriteLine("Value: "+a);
}
NOTE: The + operator is used to concatenate values. In this case, the value of a is joined to the text “Value: “.
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.
Example :
static void Print(int a) {
Console.WriteLine("Value: " + a);
}
static void Print(double a) {
Console.WriteLine("Value: " + a);
}
static void Print(string label, double a) {
Console.WriteLine(label + a);
}
static void Main(string[] args) {
Print(11);
Print(4.13);
Print("Average: ", 7.57);
}
Recommended Posts: