Curriculum
Method overloading is a feature in C# that allows us to define multiple methods with the same name in the same class, but with different parameters. The methods can differ in the number, type, or order of their parameters. This provides us with a way to create methods that perform similar operations but with different types of input.
Here is an example of method overloading in C#:
class Math { public int Add(int a, int b) { return a + b; } public double Add(double a, double b) { return a + b; } public int Add(int a, int b, int c) { return a + b + c; } }
In this example, the Math
class contains three methods called Add
, but with different parameter lists. The first method takes two integers and returns their sum, the second method takes two doubles and returns their sum, and the third method takes three integers and returns their sum. These methods have the same name but perform different operations based on their input parameters.
When we call a method that is overloaded, the compiler looks for the best match based on the number and type of arguments passed in. For example, if we call the Add
method with two integers, the compiler will choose the first Add
method that takes two integers as its input.
Here is an example of using method overloading in C#:
Math math = new Math(); int sum1 = math.Add(1, 2); // calls the first Add method double sum2 = math.Add(2.5, 3.5); // calls the second Add method int sum3 = math.Add(1, 2, 3); // calls the third Add method
In this code, we create an instance of the Math
class and call the Add
method with different parameters. The compiler chooses the appropriate method based on the input parameters.
There are several rules to keep in mind when using method overloading in C#:
In summary, method overloading is a powerful feature in C# that allows us to create methods with the same name but different parameter lists. By leveraging method overloading, we can create more flexible and reusable code that can handle a variety of input parameters.