In the previous example we saw how optional parameters can be added to method signatures. However, there was a catch that was noted about optional parameters, which is that only the last optional parameter is truly optional. This leads to an “all-or-nothing,” or, “all-except-for-the-last-one-or-nothing” situation. One way around this is with something called named parameters. All that this entails is naming the parameters, along with supplying the values, in the method call itself.
Referring to where we left off in the previous lesson, let’s demonstrate this in the call to performAttack():
Here, we (1) included the actual parameter names in the call itself, and (2) supplied the value after the colon:
Now, you can add any optional parameter and safely omit any other optional parameters by including it as a named parameter. However, it’s important to note that you still have to include every non-optional parameter in your method call even though the ordering is no longer important:
This allows us to safely omit the optional parameter that came before it:
One of the interesting features of named parameters is that they can now occur in any order you choose. This works because, normally, the order in which you supply parameter values is the only way the compiler knows which parameter you are supplying the value for. However now you are directly referring to the parameter by name:
Named parameters are a relatively new feature of C#. However, just because it’s a feature doesn’t mean you should use it under normal circumstances, as it is likely to cause confusion in your code. While rarely implemented, named parameters can have a use. For instance, you might find yourself working with a codebase that you did not originally write and you want to re-order the way the input parameters look, for the sake of clarity – but don’t want to, or can’t, change the original method definition for fear of breaking existing calls to it.
Lesson 33 - Creating Names Parameters