Dot Net For All

Method overloading in C#

Hello friends, in this article I will cover the different ways we can write multiple methods with same name. In programing terminology we call it method overloading. In this article I will discuss Method overloading in C# with a nice concept.

What is Method overloading in C#

Method overloading is to have multiple methods with different signatures in same class.

Please note that signature of method doesn’t include method return type. Only the name, number and type of input parameters in method signatures.

Method overloading is also known as compile time polymorphism. The compiler decides at the compile time which method to call. If the method. If the signature of method is not correct we will get a compile time error.

Why do we need method overloading in C#

If we want to provide the same functionality with different methods, we don’t want to rename the method every time.

Instead of writing a new name for the method every time, we can use the existing method name but with different signature.

Example of method Overloading in C#

Below is a well know and nice example to demo the method over loading in C#.

class Addition
    {
        public int Add(int a, int b)
        {
            return a + b;
        }

        public int Add(int a, int b, int c)
        {
            return a + b + c;
        }

        public double Add(int a, float b)
        {
            return a + b;
        }

        public double Add(float a, int b)
        {
            return a + b;
        }
    }

As you can see in the above code example, first and second methods are overloaded by the number of arguments.

First and third methods are overloaded by the type of parameters. Similarly first and third as well as first and forth.

Though third and fourth methods have same return type and same number of parameters. But the order of parameters is different that is why it is a valid scenario for method overloading.

Lets now create a new method with same number and type of parameters but different return type.

Method overloading gone wrong

You can see in the above screen shot, we get a compile time error.

Conclusion:

While overloading a method just keep in mind that method signatures has to be different. And return type doesn’t include method signature.

Top career enhancing courses you can't miss

My Learning Resource

Excel your system design interview