Curriculum
Member overloading, also known as function overloading, is a feature in C# that allows multiple methods to have the same name, but with different parameter lists. This allows us to create methods that perform similar operations but with different types of input.
Here is an example of member 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 member 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.
In summary, member overloading is a feature in C# that allows us to create methods with the same name, but with different parameter lists. This allows us to create methods that perform similar operations but with different types of input. When we call an overloaded method, the compiler chooses the appropriate method based on the number and type of arguments passed in.