What is method overloading in C#?

Solution

Method overloading is to define the multiple methods with the same name but having different method signature. Consider the below example.

class TestOverloading
{
        public void Print(int number)
        {
            Console.WriteLine(number);
        }

        public void Print(float number)
        {
            Console.WriteLine(number);
        }

        public void Print(int number1, int number2)
        {
            Console.WriteLine(number1+ number2);
        }

        public void Print(double number)
        {
            Console.WriteLine(number);
        }
}

In the above example, Test method have different overloads. Name of the parameter is not the part of the method signature. If we define the different name of the parameter with the same type as mentioned in the below example, then it will be the compiler error. "'TestOverloading' already defines a member called 'Print' with the same parameter types"

class TestOverloading
{
        public void Print(int number)
        {
            Console.WriteLine(number);
        }

        public void Print(int num)
        {
            Console.WriteLine(num);
        }
}

Share this thread

Comments

Comments
comments powered by Disqus

Navigation

Social Media