Unlock the Power of Method Overloading in C#

What is Method Overloading?

In C#, method overloading is a feature that allows multiple methods in a class to share the same name, as long as they have different parameters. This means that a class can have multiple methods with the same name, but with varying numbers, types, or orders of parameters.

The Magic of Overloaded Methods

Let’s take a closer look at an example of method overloading in action. Suppose we have a class with two methods, both named display(), but with different parameters. The first method takes a single integer parameter, while the second method takes two parameters – an integer and a string.

Overloading by Changing the Number of Parameters

One way to overload methods is by changing the number of parameters. In our example, we can have two methods with the same name, display(), but with different numbers of parameters.


Output:
p1.display(100) // calls the method with a single parameter
p1.display(100, 200) // calls the method with two parameters

Overloading by Changing the Data Types of Parameters

Another way to overload methods is by changing the data types of the parameters. We can have two methods with the same name, display(), but with different data types of parameters.


Output:
p1.display(100) // calls the method with an int type parameter
p1.display("Programiz") // calls the method with a string type parameter

Overloading by Changing the Order of Parameters

We can also overload methods by changing the order of the parameters. In this case, we can have two methods with the same name, display(), but with different orders of parameters.


Output:
p1.display(100, "Programming") // calls the method with int and string parameters
p1.display("Programiz", 400) // calls the method with string and int parameters

Key Takeaways

Method overloading is a powerful feature in C# that allows for more flexibility and readability in our code. By changing the number, types, or order of parameters, we can create multiple methods with the same name, making our code more efficient and easier to maintain.

Leave a Reply

Your email address will not be published. Required fields are marked *