Method Overloading in C#

Method Overloading in C# with Examples

In this article, I am going to discuss Method Overloading in C# with Examples. Please read our previous article before proceeding to this article where we discussed the basics of Polymorphism in C#. At the end of this article, you will have a very good understanding of the following pointers related to Method Overloading.

  1. What is Method Overloading in C#?
  2. When should we overload methods?
  3. What are the advantages of using Method Overloading in C#?
  4. When is a method considered as an overloaded method?
  5. What is the execution control flow of overloaded methods in C#?
  6. What is Inheritance based overloading?
  7. Real-time scenarios where you need to use Method Overloading?

Note: The point that you need to keep in mind is function overloading and method overloading terms are interchangeably used. Method overloading is one of the common ways to implement Compile-Time Polymorphism in C#.

What is Method Overloading or Function Overloading in C#?

If we are defining multiple methods with the same name but with a different signature in a class or in the Parent and Child class, then it is called Method Overloading in C#. That means C#.NET allows us to create a method in the derived class with the same name as the method name defined in the base class.

In simple words, we can say that the Method Overloading in C# allows a class to have multiple methods with the same name but with a different signature. The functions or methods can be overloaded based on the number, type (int, float, etc), order, and kind (Value, Ref or Out) of parameters. For better understanding, please have a look at the below image.

Method Overloading or Function Overloading in C#

The signature of a method consists of the name of the method and the data type, number, order, and kind (Value, Ref or Out) of parameters.

Note: The point that you need to keep in mind is that the signature of a method does not include the return type and the params modifiers. So it is not possible to overload a method just based on the return type and params modifier.

We can compare the function overloading with a person overloading. For example, if a person has already some work to do and if we are assigning some additional work to that person then the person’s work will be overloaded. In the same way, a function will have already some work to do and if we are assigning some additional work to that function, then we can say that the function is overloaded.

When should we overload methods in C#?

If you want to execute the same logic but with different types and numbers of arguments, then you need to overload the methods. For example, if you want to add two integers, two floats, and two strings, then you need to define three methods with the same name as shown in the below example.

namespace PolymorphismDemo
{
    class Program
    {
        public void add(int a, int b)
        {
            Console.WriteLine(a + b);
        }
        public void add(float x, float y)
        {
            Console.WriteLine(x + y);
        }
        public void add(string s1, string s2)
        {
            Console.WriteLine(s1 + s2);
        }
        static void Main(string[] args)
        {
            Program obj = new Program();
            obj.add(10, 20);
            obj.add(10.5f, 20.5f);
            obj.add("pranaya", "kumar");
            Console.WriteLine("Press any key to exist.");
            Console.ReadKey();
        }
    }
}
Output:

Function Overloading in C#

What are the advantages of using Method Overloading in C#? Or what are the disadvantages if we define methods with a different name?

If we overload the methods, then the user of our application gets comfort feeling in using the method with an impression that he/she calling one method by passing different types of values. The best example for us is the system-defined “WriteLine()” method. It is an overloaded method, not a single method taking different types of values.

When is a method considered as an overloaded method in C#?

If two methods have the same method name but with different signatures, then those methods are considered overloaded methods. Then the rule we should check is both methods must have different parameter types/numbers/orders. But there is no rule on return type, non-accessibility modifier and accessibility modifier means overloading methods can have their own return type, non-accessibility modifier, and accessibility modifier because overloading methods are different methods

Can we overload methods in the same class?

Yes, it is possible. No Compile Time Error, and no Runtime Error. Methods can be overloaded in the same or in super and sub classes because overloaded methods are different methods. But we can’t override a method in the same class it leads to Compile Time Error: “method is already defined” because overriding methods are the same methods with a different implementation.

What is the execution control flow of overloaded methods?

The compiler always checks for the called method definition in the reference variable type class with the given argument type parameter. So in searching and executing a method definition, we must consider both reference variable type and argument type. The Referenced variable type for deciding from which class method should be to bind. Argument type for deciding which overloaded method should be to bind.

For example:
B b = new B();
b.m1(50) => b.m1(int);

In the above method call, the compiler searches m1() method definition in the “B” class with integer parameter at the time of program compilation, and if it found that method then it binds that method definition. The compiler will searches in the B class because the type of the reference variable b is B type.

A a = new B();
a.m1(50); => a.m1(int);

In the above method call, at the time of compilation, the compiler will search m1() method definition in the “A” class with an integer parameter not in the B class even though the object is B. This is because, at compilation time, the compiler will check only the reference variable type, not the object type it holds. And here, the reference variable a type is A and it holds the object whose type is B.

What is Inheritance-Based Overloading in C#?

A method that is defined in the parent class can also be overloaded under its child class. It is called Inheritance-Based Overloading in C#. See the following example for a better understanding. As you can see in the below code, we have defined the add method twice in the ADD1 class and also defined the add method in the child ADD2 class. Here, notice every add method taking different types of parameters.

namespace PolymorphismDemo
{
    class ADD1
    {
        public void add(int a, int b)
        {
            Console.WriteLine(a + b);
        }
        public void add(float x, float y)
        {
            Console.WriteLine(x + y);
        }
    }
    class ADD2 : ADD1
    {
        public void add(string s1, string s2)
        {
            Console.WriteLine(s1 + s2);
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            ADD2 obj = new ADD2();
            obj.add(10, 20);
            obj.add(10.5f, 20.5f);
            obj.add("pranaya", "kumar");
            Console.WriteLine("Press any key to exist.");
            Console.ReadKey();
        }
    }
}
Output:

Function Overloading in C#

Note: To overload a parent class method under its child class the child class does not require any permission from its parent class.

Real-life Scenario of Method Overloading in C#

Suppose you are working on a maintenance project. And you are going to work on a class where already some parameterized constructors have been defined and you need to pass some additional parameters. So what you will do, either add the required parameter with one of the already defined constructors or add a new constructor as per your requirement. In such cases, you should not add the required parameter with the already defined constructor because this may disturb your other class dependency structure. So what you will do is create a new constructor with the required parameter. That new constructor that you are creating is nothing but the constructor overloading.

Example: Constructor Overloading in C#

Please have a look at the following example. Here, we are creating three different versions of the Constructor, and each constructor taking a different number of parameters and this is called Constructor Overloading in C#.

using System;
namespace ConstructorOverloading
{
    class ConstructorOverloading
    {
        int x, y, z;
        public ConstructorOverloading(int x)
        {
            this.x = 10;
        }
        public ConstructorOverloading(int x, int y)
        {
            this.x = x;
        }
        public ConstructorOverloading(int x, int y, int z)
        {
            this.x = x;
        }
    }
    class Test
    {
        static void Main(string[] args)
        {
            ConstructorOverloading obj1 = new ConstructorOverloading(10);
            ConstructorOverloading obj2 = new ConstructorOverloading(10, 20);
            ConstructorOverloading obj3 = new ConstructorOverloading(10, 20, 30);
            Console.ReadKey();
        }
    }
}

In the next article, I am going to discuss Method Overriding in C# with Examples. Here, in this article, I try to explain What exactly Method Overloading is in C# and when and how to use Method Overloading in C# with examples. I hope you enjoy this Method Overloading in C# with Examples article.

Leave a Reply

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