Method Overloading in C#

What is Method Overloading?

Overloaded methods are the methods that have the same name but different signatures, such as number, types, and sequence of parameters. You can define many methods with the same name but different signatures in method overloading. A method signature is the combination of the method's name along with the number, type, and order of the parameters.


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

Example of Function overloading

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Function_Oveloading
{
    class A
    {
        public void Area(int Side)
        {
            //calculate square area
            int result = Side * Side;
            Console.WriteLine("Area of a square is " + result);
        }
        public void Area(int Length, int Breadth)
        {
            //calculate rectangle area
            int result = Length * Breadth;
            Console.WriteLine("Area of a rectangle is " + result);
        }
        public void Area(double Radius)
        {
            //calculate circle area
            double pi = 3.14;
            double result = pi * Radius * Radius;
            Console.WriteLine("Area of a circle is " + result);
        }
        public double Area(double Base, double Height)
        {
            //calculate triangle area
            double result = (Base * Height) / 2;
            return result;
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            A obj = new A();
            obj.Area(15);
            obj.Area(10, 20);
            obj.Area(9.5);
            Console.WriteLine("Area of a triangle is "+obj.Area(9.5, 2.0));
            Console.ReadLine();
        }
    }
}

In the preceding code snippet, you can see that the Area() method is an overloaded method as it is defined many times with different signatures and return types.

Output of Function overloading

Area of a square is 225
Area of a rectangle is 200
Area of a circle is 283.385
Area of a triangle is 9.5

Note: Method overloading work only same class.



Write a comment


Name Email Message