Facebook Page Twitter Page LinkedIn Page
× C# Q&A


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 below example, 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 x, int y) is used. Result: "); 
    Console.Write(MyMethod(a,b)+"\n");
    Console.Write("MyMethod(float x, float y) is used. Result: "); 
    Console.Write(MyMethod(p,q)+"\n");
    Console.Write("MyMethod(int x, int y, int z) is used. Result: ");
    Console.Write(MyMethod(a,b,c)+"\n");
  }
}

The output of the above code will be:

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

❮ C# - Methods