Avoid Making Multiple Methods
Sometimes you require to pass a LOT information to a method of a given type, and you might’ve worked around it doing something like:
public MyMethodThatNeedsManyStrings(List<string> myStringList)Which in practice might seem like the way to go, but on the long run it will involve you needing to create and populate a list before passing it to this method. Where another case might be that you NEED something like the following:
public SomeMethod(string firstString) public SomeMethod(string firstString, string secondString) public SomeMethod(string firstString, string secondString, string thirdString)If you keep doing the parameter overflow like this, you can see how quickly it can become messy and hard to manage if you need to do this for, let’s say, 50 string parameters.
The premise might sound a little too specific, but it actually happens. It usually will involve you having different amounts of data to work with that you want to somehow connect in a central method:
public static class Printer { public static void Print(params string[] thingsToPrint) { foreach (string s in thingsToPrint) { // By the way, DON'T concatenate strings like this in Unity* (see below) Debug.Print("Printing: "" + s + ""."); } }* (This generates unnecessary garbage, see this)
Try It Yourself Today!
As you can see, now this little Printer is capable of printing any number of lines according to the amount of string parameters given.
Get More Useful Tips On The GitHub Wiki
What you just read about was ONE of several programmer tips that are available on the Programmer Tips Wiki.
So if you liked the one you just read, be sure to check it out (or star it) as it gets updated often! 😮
Read More Programmer Tips!I used the little params
keyword to make my StringBuilderExtension, and been using it whenever I need to since, so I hope this tip comes useful for you as well.
This concludes today’s post, hope I was helpful today~