Sorry, if duplicate.
I'm reading CLR via C#. Chapter "Parameters" starts with the explanation of optional and named parameters.
So, can you give some example where using of named parameters has some benefits, or is it just the matter of style or habit? Do you personally use named parameters?
Named parameters are very useful when combined with optional parameters in C# 4. This allows you to avoid providing a lot of method overloads, and instead just have a single one.
For example, instead of having 5 versions of a method, you can provide one method with multiple optional parameters, then call it as:
this.Foo("required argument", bar: 42);
This can simplify an API (one method instead of many), and still provide the same flexibility, without requiring the user to type in every argument. Without this, you'd either need many overloads, or have to provide all of the default values.
Besides being used with optional parameters, named parameters are sometimes useful to make code more readable.
For example:
DrawLine(10, 10, 25, 16);
If you're not familiar with this (fictional) DrawLine method, but you know the box needs to be a little taller, you'd have to look up the method to determine which parameter to change. (Is it "Left, Top, Right, Bottom" or "Top, Left, Bottom, Right" or "Top, Height, Left, Width" etc.)
But:
DrawLine(left: 10, top: 10, width: 25, height: 16);
This makes clear exactly what is intended and which parameter to adjust.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With