C# Method Overloading

Method Overloading is a form of Polymorphism. We can have multiple methods in a class with same name but different type or different number of arguments. Polymorphism? Yeah, same function in different forms.

Overload with different number of arguments

In the following example, we will define two methods that demonstrate method overloading in C#.

Program.cs

using System;

namespace CSharpExamples {
    class Calculator{
        public int add(int a, int b){
            Console.WriteLine("Adding two numbers..");
            return a+b;
        }

        public int add(int a, int b, int c){
            Console.WriteLine("Adding three numbers..");
            return a+b+c;
        }
    }
    class Program {
        static void Main(string[] args) {
            int a = 10;
            int b = 5;
            int c = 7;

            Calculator calc = new Calculator();

            int sum1 = calc.add(a,b);
            Console.WriteLine("a+b = " + sum1);

            int sum2 = calc.add(a,b,c);
            Console.WriteLine("a+b+c = " + sum2);
        }
    }
}

When we made the function call add(a+b), add function with two arguments in Calculator class is called.

Similarly, when we made the function call add(a+b+c), add function with three arguments in Calculator class is called.

Output

Adding two numbers..
a+b = 15
Adding three numbers..
a+b+c = 22
ADVERTISEMENT

Overload with different datatypes of arguments

Similarly we can overload functions with arguments of different datatypes.

Program.cs

using System;

namespace CSharpExamples {
    class Calculator{
        public int add(int a, int b){
            Console.WriteLine("Adding two integers..");
            return a+b;
        }

        public float add(int a, float c){
            Console.WriteLine("Adding integer and float..");
            return a+c;
        }
    }
    class Program {
        static void Main(string[] args) {
            int a = 10;
            int b = 5;
            float c = 7.4F;

            Calculator calc = new Calculator();

            int sum1 = calc.add(a,b);
            Console.WriteLine("a+b = " + sum1);

            float sum2 = calc.add(a,c);
            Console.WriteLine("a+b+c = " + sum2);
        }
    }
}

When you make the function call add(a, b), the add function with two int arguments is executed.

When you make the function call add(a, c), the add function with int and float arguments is executed.

Output

Adding two integers..
a+b = 15
Adding integer and float..
a+b+c = 17.4

Conclusion

In this C# Tutorial, we learned what Method Overloading is in C#, with the help of example programs.