C# Method Overloading

In C#, method overloading allows multiple methods to have the same name, but with different parameters. This makes code more readable and allows you to reuse the same method name in different contexts. Method overloading is a feature of object-oriented programming (OOP) that simplifies code and reduces the amount of code that you have to write.

Declaring Method Overloading

To declare method overloading in C#, you need to define two or more methods with the same name but different parameters. The parameters can be of different types, different number of parameters or different order of parameters. Method overloading is also called compile-time polymorphism because the method to be called is decided at compile-time based on the parameters passed.

1class Calculator 2{ 3 public int Add(int num1, int num2) 4 { 5 return num1 + num2; 6 } 7 8 public int Add(int num1, int num2, int num3) 9 { 10 return num1 + num2 + num3; 11 } 12 13 public double Add(double num1, double num2) 14 { 15 return num1 + num2; 16 } 17}

In the above code snippet, we have a Calculator class that has three different methods named Add. The first method takes two integers as input and returns their sum. The second method takes three integers as input and returns their sum. The third method takes two doubles as input and returns their sum.

Calling Method Overloading

When calling a method, C# uses the number and types of the arguments to determine which method to call. The following code shows how to call the Add method with different arguments:

1Calculator calculator = new Calculator(); 2 3int result1 = calculator.Add(1, 2); // result1 = 3 4int result2 = calculator.Add(1, 2, 3); // result2 = 6 5double result3 = calculator.Add(1.5, 2.5); // result3 = 4.0

In the above code, we first create an instance of the Calculator class. We then call the Add method three times with different arguments. The first call to Add passes two integers, the second call passes three integers, and the third call passes two doubles.

Method Overloading with Different Parameters

Method overloading can also be done with different types of parameters, such as int and string:

1class Example 2{ 3 public void Test(int a) 4 { 5 Console.WriteLine("Method with int parameter: {0}", a); 6 } 7 8 public void Test(string b) 9 { 10 Console.WriteLine("Method with string parameter: {0}", b); 11 } 12}