C# Member overloading

If we define two members in a class with the same name then it's called member overloading. Advantage of member overloading is the thing that we don't need to give different names to the members of the same meaning and are defined for the same purposes. In C#, we can overload constructors, methods and index properties since they have parameters defined in their signature.

C# Method overloading: In a class, if we defined two methods with the same name but different signature then it's called method overloading. To overload a method we need to:
  1. Change the number of parameters.
  2. Change the data type of parameters.
C# Method overloading example: by changing number of parameters
using System;
public class Calculation
{
            public int addition(int a,int b)
            {
                        return a+b;
            }

            public int addition(int a,int b,int c)
            {
                        return a+b+c;
            }
}
public class OverLoadingExample
{
            public static void Main (string[] args)
            {
                        Calculation cal=new Calculation();
                        Console.WriteLine(cal.addition(10,20));
                        Console.WriteLine(cal.addition(10,20,30));
            }
}
C# Method Overloading Example: by changing data type of parameters
using System;
public class Calculation
{
            public int addition(int a,int b)
            {
                        return a+b;
            }
            public float addition(int a,float b)
            {
                        return a+b;
            }
}
public class OverLoadingExample
{
            public static void Main (string[] args)
            {
                        Calculation cal=new Calculation();
                        Console.WriteLine(cal.addition(10,20));
                        Console.WriteLine(cal.addition(10,20.6f));
            }
}
C# Type Promotion in method overloading: In C#, one data type is promoted to another if no matching is found between function call and function definition. Let's see an example of type promotion in method overloading. The float In the function call is automatically promoted to double of function signature defined.
using System;
public class Calculation
{
            public long addition(int a,long b)
            {
                        return a+b;
            }
            public double addition(int a,double b)
            {
                        return a+b;
            }
}
public class OverLoadingExample
{
            public static void Main (string[] args)
            {
                        Calculation cal=new Calculation();
                        Console.WriteLine(cal.addition(10,20));
                        Console.WriteLine(cal.addition(10,20.6f));
            }
}
Output
30
30.6000003814697



ADVERTISEMENT
ADVERTISEMENT