[Solved] C# overloaded methods


Two methods with the same name but different signatures is called overloaded method. At compile time Compiler will identify the method based on the method signature even though the name of the method is same.

void Add(int x, int y)
{
    Console.WriteLine("Add int");
}
void Add(double x, double y)
{
    Console.WriteLine("Add double");
} 

Here the Add(double x, double y) overlaods the first fuction Add(int x, int y) same name different signatures.
If we call Add(4,2) it will call the Add(int x, int y) function
and if we call Add(4.0,2.0) it will call the Add(double x, double y) function.

Criteria for method overloading.

  1. Same name different signature.
  2. Different number of arguments or Different types of arguments or Different order of arguments.

  3. Can’t overload method by Changing the return type of the method. Because return value alone is not sufficient for the compiler to figure out which method to call. Also the return type of a method is not considered to be part of a method’s signature.

Also note, the out and ref parameter modifies can be used to differinate to overloads, like so:

void method1(int x);
void method1(out int x);

void method2(char c);
void method2(ref char c);

However, you cannot do this:

void method(out int x);
void method(ref int x);

As ref and out do not differentiate from one another, in an overload sense.
And be careful with overloads like this:

void method(int x) => Console.Writeline(x);
void method(int x, int y = 0) => Console.Writeline(x * y);

This will compile and work, but the compiler will default to the first method that has one parameter, until you specify the second parameter, then it will call the second method.

solved C# overloaded methods