Method overloading is a technique in which you create multiple methods with the same name but different parameter lists in the same class. This allows you to provide multiple implementations of a method that can be called depending on the number and types of arguments passed to the method.
Here’s an example of how to overload a method in C#:
public 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 have created two Add
methods: one that takes two int
arguments and one that takes two double
arguments. When you call the Add
method with two int
arguments, the compiler will execute the first version of the method, and when you call it with two double
arguments, it will execute the second version.
Read More: How to Create and Use Constructors in C#
You can also overload a method by using default values for some of the parameters. For example:
public class Calculator { public int Add(int x, int y, int z = 0) { return x + y + z; } }
In this case, you can call the Add
the method with either two or three arguments. If you call it with two arguments, the compiler will use the default value of 0
for the z
parameter.
It’s important to note that when overloading a method, the parameter types and the number of parameters must be different. You cannot overload a method by only changing the return type or the access modifier (such as public
or private
).