Introduction

Method overloading is where a method in the same class can have the same name but with different parameters. They can have different data types, order, and number of parameters. The compiler does not look at the return type when comparing the methods with the same name. Rather, it looks at the number of parameters and their data types. If the methods have the same parameters, but their return types are different, the compiler will throw an error.

In addition to sharing the same name, methods are considered overloaded if:

  • The parameters in the methods are in a different order.
  • The data types in the method parameters are different.
  • The number of parameters in the methods are different.

Therefore, what we are doing is applying Polymorphism. We are redefining the methods in different forms.

Examples

Parameters that are in a different order

public class Program
{
    public string NameAge (string Name, int age)
    {
       	return Name + " " + age;
    }

    public string NameAge (int age, string Name)
    {
       	return age + " " + Name;
    }
}

The data types of the two methods are different

public class Program
{
   public int Sum(int x, int y)
   {
 	 return x + y;	
   }	
	
   public double Sum(int x, double y)
   {
 	 return x + y;	
   }
}

The number of parameters in the methods are different

public class Program
{
	public int Sum(int x, int y)
	{
		return x + y;	
	}
	
	public int Sum(int x, int y, int z)
	{
		return x + y + z;
	}
}

The same number of parameters, but different return types

public class Program
{
   public int Sum(int x, int y)
   {
	 return x + y;	
   }
	
   public double Sum(int x, int y)
   {
	 return x + y;
   } 
}

The above example will result in a compiler error.