Why it is sometimes to use params?
Imagine, that you have a lot of code, that is complicated, hard to maintain and you have a small amount of time to make a change in it. For example, you need to change a parameter (e.g. width, height, color etc.) of a controls with a specific tag. Those controls may be placed on many different screens, but unfortunatly they can be sometimes removed from the screen.
To solve this problem you can use a list of controls (remember to check if it is not a NULL!) or you can use params.
Using of the keyword params gives a possibility to pass to the method a comma-separated set of arguments of one type or an array of arguments of one type. The great thing about params is that passing the argument is not mandatory and it is recognized as an empty collection and not as a null. It is useful especially if we are not sure if there are elements and we do not want (or can't for some reasons) to make null-checks.
Example
Lets take a look on the example. We have a simple WPF application with some controls and a button with a handler.
Thehere is also a method, that changes the width of the controls, that are marked with the specific Tag.
private static void ChangeWidth(params Control[] allControls) { foreach (Control ctcw in allControls) { if (ctcw.Tag != null && ctcw.Tag.ToString() == "ToChangeWidth") { ctcw.Width = 100; } } }
As you see, the controls array is preceded by the keyword params. Now in a handler we can test how the params works.
public MainWindow() { InitializeComponent(); } private void Button_Click(object sender, RoutedEventArgs e) { // 1 - No change of the controls width, but also no error. ChangeWidth(); // 2 - //All controls with tag "ToChangeWidth" will have new width Control[] allControls = mainGrid.Children.OfType().ToArray(); ChangeWidth(allControls); // 3 - //Throws exception ! ChangeWidth(null); }
The great thing is that in first two cases the solution will work. Remember, that passing a null value to the method will work as usual, so in the foreach loop it will throw an error. Only NOT passing any parameter will (in fact) pass empty array to the method.
Why is it worth using?
- It is faster than a List, because in fact, the compiler creates an array of objects of the given type instead of a List.
- It is useful if you need to pass unknown number of the parameters.
- You can easy read the code and understand it, because there is less code to write.
- In some cases you do not need to write the null-checks (but they are usually a safe solution!).