C# Tutorial C# Advanced C# References

C# - Method Overloading



With method overloading feature in C#, two or more methods can have the same name but different parameters. It allows the programmer to write methods to perform conceptually the same thing on different types of data without changing the name.

Example:

In the example below, three methods with the same name MyMethod are created. First method takes two integer numbers as arguments and returns sum of these numbers. The second method takes two float numbers as arguments and returns sum of these numbers. The third method takes three integer numbers as arguments and returns sum of these numbers.

using System;

class MyProgram {
  static int MyMethod(int a, int b) {
    return a + b;
  }
  static float MyMethod(float a, float b) {
    return a + b;
  }
  static int MyMethod(int a, int b, int c) {
    return a + b + c;
  } 

  static void Main(string[] args) {
    int a = 100, b = 10, c = 1;
    float p = 500.5f, q = 50.05f;

    Console.Write("MyMethod(int, int) is used. Result: "); 
    Console.Write(MyMethod(a,b)+"\n");
    Console.Write("MyMethod(float, float) is used. Result: "); 
    Console.Write(MyMethod(p,q)+"\n");
    Console.Write("MyMethod(int, int, int) is used. Result: ");
    Console.Write(MyMethod(a,b,c)+"\n");
  }
}

The output of the above code will be:

MyMethod(int, int) is used. Result: 110
MyMethod(float, float) is used. Result: 550.55
MyMethod(int, int, int) is used. Result: 111

❮ C# - Methods