Objects in this mirror are closer to Microsoft Technologies. DNM objective is to help users on Microsoft technologies by providing Articles, snippets, Interview Questions.

07 July 2012

Method overloading in C#

In this article we will discuss about method overloading concept with examples.

Definition: Method overloading is a concept of using same method name with differing in the number type and order of arguments.

 Example: if we want to add two integers or two float values we can write methods like
Before method overloading
After method overloading
public int AddIntValues(int a1, int a2)
            {
                return a1 + a2;
            }
public float AddFloatValues(float a1, float a2)
            {
                return a1 + a2;
            }
public int Add(int a1, int a2)
            {
                return a1 + a2;
            }
            public float Add(float a1, float a2)
            {
                return a1 + a2;
            }

The compiler will identify which method to execute based on number of arguments and their data types during compilation. 

Below is the example which shows method overloading.

Example:
class Base
    {
        public int Add(int a1, int a2)
        {
            return a1 + a2;
        }
        public float Add(int a1, float a2)
        {
            return a1 + a2;
        }
    }
    class Derived : Base
    {
        public int Add(int a1, int a2, int a3)
        {
            return a1 + a2 + a3;
        }
        public float Add(float a1, int a2)
        {
            return a1 + a2;
        }
    }
 
    class MethodOverloadingUsage
    {
        static void Main()
        {
            Derived obj = new Derived();
            Console.WriteLine(obj.Add(10, 20));
            Console.WriteLine(obj.Add(10, 12.5f));
            Console.WriteLine(obj.Add(10, 20, 30));
            Console.WriteLine(obj.Add(13.5f,10));
            Console.Read();
        }
    }
Output:
30
22.5
60
23.5

When to use: If a method is performing similar action but using different parameters then we can use method overloading.

Data points:
  • Return type of method will not considered for overloading usage
  • Same method name provides different forms so it is example of polymorphism.
  • In method overloading the method name should be same. Parameters (data type and order) and return type can be different for each method which is overloaded.

0 Comments:

Post a Comment