What is Method Overloading in C#: Simple Explanation and Example
method overloading means creating multiple methods with the same name but different parameters in the same class. It allows you to perform similar actions with different types or numbers of inputs, making your code easier to read and use.How It Works
Method overloading in C# works by defining several methods that share the same name but differ in the number, type, or order of their parameters. When you call the method, the compiler decides which version to run based on the arguments you provide.
Think of it like ordering coffee: you can ask for a "coffee" but specify if you want it black, with milk, or with sugar. The barista understands your request based on what you say, even though the main order name is the same. Similarly, method overloading lets you use one method name for related actions but with different details.
Example
This example shows a class with three Print methods that take different parameters. The program calls each one, and the correct method runs based on the input.
using System; class Printer { public void Print(string message) { Console.WriteLine("Message: " + message); } public void Print(int number) { Console.WriteLine("Number: " + number); } public void Print(string message, int times) { for (int i = 0; i < times; i++) { Console.WriteLine("Repeated: " + message); } } } class Program { static void Main() { Printer printer = new Printer(); printer.Print("Hello"); printer.Print(123); printer.Print("Hi", 3); } }
When to Use
Use method overloading when you want to perform similar actions but with different kinds or amounts of information. It helps keep your code clean and easy to understand by avoiding many different method names for related tasks.
For example, if you have a logging system, you might want to log just a message, a message with a severity level, or a message with extra details. Overloading lets you use the same method name Log for all these cases.
Key Points
- Method overloading means multiple methods share the same name but differ in parameters.
- The compiler chooses the right method based on the arguments you pass.
- It improves code readability and organization.
- Overloaded methods must differ in parameter type, number, or order.
- Return type alone cannot distinguish overloaded methods.