Method Overloading is a powerful feature in C# that allows multiple methods to share the same name, as long as they have different parameters.
This makes your code cleaner, more intuitive, and easier to use.
Normally, you cannot have two methods with the exact same name in the same class. The compiler wouldn't know which one you are trying to call!
However, if the methods have a different signature (meaning they take different types or numbers of parameters), the C# compiler is smart enough to figure out which one you want based on the arguments you pass in.
Consider the following example where we want to add numbers. Without overloading, we might have to create differently named methods for different data types:
int AddIntegers(int x, int y) { return x + y; }double AddDoubles(double x, double y) { return x + y; }
Having to remember AddIntegers and AddDoubles is tedious. Method overloading solves this elegantly.
With method overloading, multiple methods can have the same name with different parameters:
using System;namespace MyApplication { class Program { // Method for integers static int PlusMethod(int x, int y) { return x + y; } // Method for doubles (same name!) static double PlusMethod(double x, double y) { return x + y; } static void Main(string[] args) { int myNum1 = PlusMethod(8, 5); double myNum2 = PlusMethod(4.3, 6.26); Console.WriteLine("Int: " + myNum1); Console.WriteLine("Double: " + myNum2); } } }
When you call PlusMethod(8, 5), the compiler sees you passed two int values, so it executes the integer version. When you pass 4.3 and 6.26, it executes the double version!
You can also overload methods by changing the number of parameters they accept.
using System;namespace MyApplication { class Program { static void PrintInfo(string name) { Console.WriteLine("Name: " + name); } static void PrintInfo(string name, int age) { Console.WriteLine("Name: " + name + ", Age: " + age); } static void Main(string[] args) { PrintInfo("Alice"); // Calls the first method PrintInfo("Bob", 25); // Calls the second method } } }
For method overloading to work, the methods must have different signatures. A method signature consists of:
Crucial Note: The return type of a method is not part of its signature. You cannot overload two methods if they only differ by their return type. Doing so will result in a compiler error.
Invalid Overloading Example:
// This will cause a compiler error! static int Calculate(int x) { return x; } static double Calculate(int x) { return x; }
Method overloading allows multiple methods to have the same name as long as they have...