Method Overloading in C# with Example

Method Overloading in C# with Example
Rating: 5 - 1 Votes

Method Overloading in C# with Example

Method Overloading in C# with Example

Method Overloading in C# with Example

We know very well how to create methods in C#.  We basically create methods to increase the code reusability.  Suppose if you want to add 2 numbers, you can create a method by the name of add_number with 2 parameters of type integer.  Same goes in case of adding or concatenating 2 strings, you can create a method by the name of add_string with 2 parameters of type string.  If you have a large number of methods like this in your project, it will be pretty much cumbersome to remember the name of each and every method, which eventually perform a same job, but only differ in signature and method name.  Signature of the method includes number of parameters, data type of parameter, and parameter modifier like out, ref.

To make the job easier, we make use of Method Overloading.  Method overloading will give you the ability to have multiple methods with same name, but with different signature.  Signature of the method does not include method return type and params parameter modifier, so you cannot overload any method based on that.  For the above given example, you can easily create 2 Add methods, one which will have 2 parameters of integer type and another one which will have 2 parameters of string type.

 Output:

Number: 30
String: Hello World