find and solve || findandsolve.com
Please wait.....

C# Member overloading Example

This is called member overloading in C# programming language when we create two or more members having the same name but different in number or type of parameter.

n C#, you can overload

  • methods,
  • constructors, and
  • indexed properties

C# Method Overloading

Having two or more methods with the same name but different parameters are known as method overloading in C#.

The advantage of method overloading is that it increases the readability of the program because we don't need to use different names for the same action.

We can perform method overloading in C# by two ways:

  • By changing the number of arguments
  • By changing the data type of the arguments

C# Method Overloading Example: By changing no. of arguments

using System;  

public class Example{
    public static int Add(int firstNumber,int secondNumber){
        return firstNumber + secondNumber;
    }
    public static int Add(int firstNumber,int secondNumber, int thirdNumber)
    {
        return firstNumber + secondNumber + thirdNumber;
    }
}
public class MemberOverloadingExample
{
    public static void Main()
    {
        Console.WriteLine(Example.Add(10, 24));
        Console.WriteLine(Example.Add(13, 102, 34));
    }
}  

Output

34

149


C# Member Overloading Example: By changing data type of arguments

using System;  

public class Example{
    public static int Add(int firstNumber,int secondNumber){
        return firstNumber + secondNumber;
    }
    public static float Add(float firstNumber,float secondNumber)
    {
        return firstNumber + secondNumber;
    }
}
public class MemberOverloadingExample
{
    public static void Main()
    {
        Console.WriteLine(Example.Add(10, 24));
        Console.WriteLine(Example.Add(13.12f, 102.23f));
    }
}  

Output

34

115.35