#594 – When You’d Want to Use Named Arguments
May 30, 2012 Leave a comment
You can change the order of arguments passed to a method in C# by using named arguments. Simply changing the order of required arguments probably doesn’t make much sense. Instead, you’ll likely make use of named arguments as a way of omitting optional parameters.
Without named arguments, when you want to include a value for an optional parameter, you normally have to include values for all arguments up to and including the one that you want to specify a value for. But with named arguments, you can pick and choose which parameters you provide a value for.
Here’s a Dog.Bark method that has several optional parameters.
public void Bark(string barkSound, int numTimesToBark = 1, int volume = 1, string postBarkSound = null)
When calling Bark, we can choose which arguments to pass.
kirby.Bark("Woof", volume: 5); kirby.Bark("Grrr", postBarkSound: "Arf"); kirby.Bark("Woof", 3, postBarkSound: "Growf");