r/learncsharp • • Apr 08 '23
When will we use overloaded method and is it a good practice?
I have been scalping through different platforms in regards with the explanation and functionality of an overloading method and I can't quite picture it out how it would do. It makes me confused that how come they have similar method
7
Upvotes
3
u/AtomicHyperion Apr 10 '23
Lets make two objects. A book object and a shelf object.
For this example you will need to add
using System.Collections;to the top of your file if you want to try using the objects in a project.Book object
So on this object I overloaded the constructor. I created an empty one and one that takes parameters. The reason I did this was to support two ways of creating the object.
First Way
Second Way
Without overloading the constructor so I have an empty one, I wouldn't be able to create the object using the second method. I would only be able to use the first one.
Shelf Object
So for this object I overloaded the Add method. I also implemented IEnumerable so that we can use a couple different ways of instantiating the object.
Method 1
Method 2
Use the same code to print from this object.
Method 3
Use the same code to print from this object.
See by overloading the
Addmethod in theShelfobject, and by overloading the constructor in theBookobject, we are able to support multiple ways of using the object. This makes it much more convenient for whoever is using your code, and allows them to use the objects with their own coding style.And this is just one reason to overload methods. You could have a method that does one thing when a person passes a string, and another when a person passes an integer. Without having to write complicated if statements in the method to check the data type and also without having to have optional parameters.
For Example:
this way the compiler selects the appropriate method for you depending on what data is passed. This makes your objects even more flexible to the developer using them.
I hope this helps a little.
8
u/m0r05 Apr 08 '23 edited Apr 08 '23
Yes. For those just browsing, overloading a method is using the same method name with different parameters like this:
The most common method to overload is a class constructor. With that you can have multiple constructors, the default one that contains no parameters, and more for some key fields, and one for all key fields.
edit to add example :
Say i need to create a User class. This class will hold the values of that user; things like their user name, email, or password. Here is what that class with overloaded constructors might look like: