blog

Home / DeveloperSection / Blogs / Method Overloading in C#

Method Overloading in C#

Sumit Kesarwani4327 13-May-2013

In this article, I’m trying to explain the concept of method overloading.Method overloading is the concept of polymorphism which means one name multiple forms. It defines that method can have same name with different parameters or signatures. It allows you to have same name method in one class. In method overloading, method performs different tasks at the different input parameters.

Method overloading requires:

1 - Same method name.

2 - Number of parameters should be different.

3 - Types of parameters should be different.

To implement the method overloading, the methods must have same name and the numbers of parameters or data types of parameters must be different, having different return types of method does not make the method overloaded. 

Example

using System;
namespaceMethodOverLoadingConsoleApplication
{
    classMethodOverloading
    {
        /// <summary>
        /// mehtod area(int side) for calculating the area of square
        /// </summary>
        /// <param name="side">side of square</param>
        publicvoidarea(intside)
        {
            intz=side*side;
            Console.WriteLine("Area Of Square : "+z);
        }
        /// <summary>
        /// mehtod area(int length,int width) for calculating the area of rectangle
        /// </summary>
        /// <param name="length">length of rectangle</param>
        /// <param name="width">width of rectangle</param>
        publicvoidarea(intlength,intwidth)
        {
            intz=length*width;
            Console.WriteLine("Area Of Rectangle : "+z);
        }
    }
    classProgram
    {
        staticvoidMain(string[] args)
        {
            MethodOverloadingmth=newMethodOverloading();//Create object
            mth.area(4);
            mth.area(7,5);
        }
    }
}

 

Output :

Area Of Square : 16

Area Of Rectangle :  35

In this example, i have created two methods with the name area() - one for calculating  the area of square and another for rectangle, note that both the methods have same name but different  number of parameters which make the methods overloaded.


Updated 18-Sep-2014

Leave Comment

Comments

Liked By