c-sharp
  1. c-sharp-member-overloading

C# Method Overloading

In C#, method overloading is the process of defining multiple methods with the same name but different parameters. This allows us to use the same method name for similar operations with different input parameters. In this tutorial, we'll discuss how to use method overloading in C#.

Syntax

The syntax for method overloading in C# is as follows:

public void MyMethod(int param1) {
  // code
}

public void MyMethod(string param1) {
  // code
}

In the example above, we define two methods with the same name "MyMethod" but they accept a different type of parameter (int and string).

Example

Let's say we want to create a class with a method that multiplies two numbers. We want the method to work with both integers and floating-point numbers. We can use method overloading to accomplish this:

public class MathHelper {
   public int Multiply(int x, int y) {
      return x * y;
   }

   public double Multiply(double x, double y) {
      return x * y;
   }
}

Now, we can use the MathHelper class to multiply two numbers, regardless of whether they are integers or floating-point values:

MathHelper mh = new MathHelper();
int result1 = mh.Multiply(3, 4);
double result2 = mh.Multiply(2.5, 3.5);
Console.WriteLine(result1); // Output: 12
Console.WriteLine(result2); // Output: 8.75

Output

When we run the example code above, the output will be:

12
8.75

This is because the MathHelper class has two overloads of the Multiply method that accept different parameter types.

Explanation

In the example above, we created a class called "MathHelper" with two overloads of the "Multiply" method. One overload accepts two integers, while the other accepts two floating-point numbers. We can instantiate the MathHelper class and use its methods to multiply two numbers, regardless of whether they are integers or floating-point values.

Use

Method overloading is useful when you want to provide the same operation on multiple types of input parameters. This can help reduce code duplication and improve code readability.

Important Points

  • Method overloading is based on the number, type, and order of parameters in a method.
  • Method overloads cannot differ in only their return type.
  • Method overloading is resolved at compile-time, not runtime.

Summary

In this tutorial, we discussed how to use method overloading in C#. We covered the syntax, example, output, explanation, use, and important points of method overloading in C#. With this knowledge, you can now use method overloading in your C# code to provide the same operation on multiple types of input parameters.

Published on: