Saturday, May 13, 2023

Method overloading in C#| Method overloading

 What is method overloading in c#?


Method overloading in C# allows you to define multiple methods with the same name in a single class, as long as they have different method signatures (i.e. different parameters). When you call a method with an overloaded name, the compiler determines which version of the method to call based on the arguments that you provide.


Here is an example of method overloading in C#:



class Calculator

{

    public int Add(int x, int y)

    {

        return x + y;

    }


    public double Add(double x, double y)

    {

        return x + y;

    }

}



In this example, we define a class called "Calculator" with two methods called "Add". The first method takes two integers as parameters and returns their sum, while the second method takes two doubles as parameters and returns their sum. When we call the "Add" method, the compiler will choose the appropriate method based on the types of the arguments that we provide. For example:



Calculator calc = new Calculator();

int result1 = calc.Add(3, 4); // calls the int Add(int x, int y) method

double result2 = calc.Add(3.0, 4.0); // calls the double Add(double x, double y) method



Method overloading can be very useful in C# because it allows you to define multiple methods with similar functionality, but with different input and output types. This can make your code more flexible and easier to read, because you can use the same method name to represent different operations.

No comments:

Post a Comment

If you have any query kindly let me know.

Blazor drawback| drawback of blazor| Disadvantage of blazor in c#

  Blazor drawback| drawback of blazor| Disadvantage of blazor in c# While Blazor offers many advantages, it also has a few drawbacks to cons...