C# Method Overloading
Method overloading in C# allows you to create multiple methods with the same name but different parameters within the same class. It enables methods to handle different types or numbers of inputs, providing flexibility and readability in your code.
What You Will Learn
- Understanding Method Overloading
- Creating Overloaded Methods with Different Parameter Types
- Creating Overloaded Methods with Different Numbers of Parameters
- Limitations and Best Practices
Understanding Method Overloading
Method overloading allows a class to have multiple methods with the same name but different signatures. The method signature consists of the method name and the parameter list (type, number, and order of parameters). Return type is not part of the method signature for overloading purposes.
Example 1: Overloading Methods with Different Parameter Types
class Calculator
{
// Method to add two integers
public int Add(int a, int b)
{
return a + b;
}
// Overloaded method to add two doubles
public double Add(double a, double b)
{
return a + b;
}
}
class Program
{
static void Main(string[] args)
{
Calculator calc = new Calculator();
int intResult = calc.Add(5, 10);
double doubleResult = calc.Add(5.5, 10.5);
Console.WriteLine("Integer Addition: " + intResult);
Console.WriteLine("Double Addition: " + doubleResult);
}
}
Output:
Integer Addition: 15 Double Addition: 16
Explanation: The Calculator
class has two methods named Add
. One takes two integers, and the other takes two doubles. Depending on the arguments passed, the appropriate method is called.
Example 2: Overloading Methods with Different Numbers of Parameters
class Printer
{
// Method to print a string
public void Print(string message)
{
Console.WriteLine(message);
}
// Overloaded method to print a string multiple times
public void Print(string message, int times)
{
for (int i = 0; i < times; i++)
{
Console.WriteLine(message);
}
}
}
class Program
{
static void Main(string[] args)
{
Printer printer = new Printer();
printer.Print("Hello, World!"); // Calls the first method
printer.Print("Hello, C#!", 3); // Calls the overloaded method
}
}
Output:
Hello, World! Hello, C#! Hello, C#! Hello, C#!
Explanation: The Printer
class has two methods named Print
. The first method prints a message once. The overloaded method takes an additional parameter to specify how many times to print the message.
Limitations and Best Practices
While method overloading is powerful, there are limitations and best practices to consider:
- You cannot overload methods by changing only the return type.
- Parameters must differ in type, number, or order.
- Overusing overloading can make code confusing; use it judiciously.
Recall
- Method Overloading: Defining multiple methods with the same name but different parameters.
- Method Signature: Consists of the method name and parameter list.
- Parameters: Must differ in type, number, or order for overloading.
- Return Type: Cannot overload methods by return type alone.