C# Method Overloading

In c#, Method Overloading means defining multiple methods with the same name but with different parameters. Using method overloading, we can perform different tasks with the same method name by passing different parameters.

 

If we want to overload a method in c#, then we need to define another method with the same name but with different signatures. In c#, the Method Overloading is also called compile time polymorphism or early binding.

 

Following is the code snippet of implementing a method overloading in the c# programming language.

 

public class Calculate
{
    public void AddNumbers(int a, int b)
    {
       Console.WriteLine("a + b = {0}", a + b);
    }
    public void AddNumbers(int a, int b, int c)
    {
       Console.WriteLine("a + b + c = {0}", a + b + c);
    }
}

If you observe the above “Calculate” class, we defined two methods with the same name (AddNumbers) but with different input parameters to achieve method overloading in c#.

C# Method Overloading Example

Following is the example of implementing a method overloading in the c# programming language.

 

using System;

namespace Tutlane
{
    public class Calculate
    {
        public void AddNumbers(int a, int b)
        {
           Console.WriteLine("a + b = {0}", a + b);
        }
        public void AddNumbers(int a, int b, int c)
        {
           Console.WriteLine("a + b + c = {0}", a + b + c);
        }
    }
    class Program
    {
       static void Main(string[] args)
       {
          Calculate c = new Calculate();
          c.AddNumbers(1, 2);
          c.AddNumbers(1, 2, 3);
          Console.WriteLine("\nPress Enter Key to Exit..");
          Console.ReadLine();
       }
    }
}

When you execute the above c# program, you will get the result as shown below.

 

C# Method Overloading Example Result

 

This is how we can implement method overloading in c# by defining multiple methods with the same name but with different signatures based on our requirements.