Home > DeveloperSection > Blogs > Method Overloading in C#

Method Overloading in C#


C# C# 
Ratings:
0 Comment(s)
 1437  View(s)
Rate this:

Method Overloading in C#

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;

namespace MethodOverLoadingConsoleApplication

{

    class MethodOverloading

    {

        /// <summary>

        /// mehtod area(int side) for calculating the area of square

        /// </summary>

        /// <param name="side">side of square</param>

        public void area(int side)

        {

            int z = 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>

        public void area(int length,int width)

        {

            int z = length * width;

            Console.WriteLine("Area Of Rectangle : " + z);

        }

    }

    class Program

    {

        static void Main(string[] args)

        {

            MethodOverloading mth = new MethodOverloading();//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.


Don't want to miss updates? Please click the below button!

Follow MindStick