C# Method Overloading

Updated on     Kisan Patel

It is possible to have more than one method with the same name and return type but with a different number and type of arguments (parameters) passed to it. This is called method overloading.

For Example,

class Shape
{
    public void Area(int side)
    {
        int SquareArea = side * side;
        Console.WriteLine("The Area of Square is : " + SquareArea);
    }

    public void Area(int Length, int Breadth)
    {
        int RectangleArea = Length * Breadth;
        Console.WriteLine("The Area of Rectangle is : " + RectangleArea);
    }

    public void Area(double Radius)
    {
        double CircleArea = 3.14 * Radius * Radius;
        Console.WriteLine("The Area of Circle is : " + CircleArea);
    }

}

So, In method overloading, you can define many methods with the same name but different signature.

When you call overloaded method, a compiler automatically determine which method should be used according to the signature specified in the method call.

using System;

namespace ConsoleApp
{
    class Shape
    {
        public void Area(int side)
        {
            int SquareArea = side * side;
            Console.WriteLine("The Area of Square is : " + SquareArea);
        }

        public void Area(int Length, int Breadth)
        {
            int RectangleArea = Length * Breadth;
            Console.WriteLine("The Area of Rectangle is : " + RectangleArea);
        }

        public void Area(double Radius)
        {
            double CircleArea = 3.14 * Radius * Radius;
            Console.WriteLine("The Area of Circle is : " + CircleArea);
        }

    }

    class ShapeTester
    {
        public static void Main(string[] args)
        {
            Shape obj = new Shape();
            obj.Area(10.0);
            obj.Area(15);
            obj.Area(10, 20);
        }
    }
}

The output of the above C# program…

c-sharp-method-overloading-demo

In above example, the Area() method of Shape class is overloaded for calculating the areas of square, rectangle and circle shapes.

In the Main() method, the Area() method is called multiple times by passing different arguments.


C#

Leave a Reply