What is Method Overloading in C# and How to Use It?

Method Overloading is required when you have a class and you want that class to perform some tasks in different ways. For example, Method overloading is required if you want a single function in a class that is designed to add two numbers together, you want to extend its functionality. You want that same function to add 3 numbers.

You need two have two different methods with the same name but different signatures. If you don’t understand what is signature In a function. A signature in a function is the number of parameters that function takes.

When we will make the instance of this class, it will show you only one function in that class and will have 2 different definitions of this method. Do not worry if you don’t understand anything, we will understand it in this article with an example program.

What-is-Method-Overloading-in-C-mid-Image

Method Overloading Definition

Inside a class when we have multiple definitions of a method, and the class implements the correct definition based on the method signature, this is called Method Overloading.

Method Signature

The signature of a method is the number of parameters that it receives from the user.

public int Add(int a, int b)
        {
            int c = a + b;
            return c;
        }

In the above example (int a, int b) is the method signature.

Method Overloading Example

using System;
namespace Polymorphism
{
    class Calculation
    {
        public int Add(int a, int b)
        {
            int C = a + b;
            return C;
        }
        public int Add(int a, int b, int c)
        {
            int C = a + b + c;
            return C;
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            int num;
            Calculation Cal = new Calculation();
            num = Cal.Add(2,2,4);
            Console.WriteLine(num);
            Console.ReadLine();
        }
    }
}

Explanation

As you can see in the code above, we have two methods inside the Calculation class. One method is to add two integers and the other is for adding three integers together. At runtime, the correct definition of the method will be called based on the number of parameters the class receives from the user. This is called Method Overloading.

Method Overloading Concept is provided by Microsoft C#. Method Overloading is a part of Polymorphism. I hope you have understood it. In case of any confusion, feel free to comment. I will be glad to help you further with it.

Till then Stay Safe Stay Healthy!

Share your love
Nadeem
Nadeem

Leave a Reply

Your email address will not be published. Required fields are marked *