#594 – When You’d Want to Use Named Arguments

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");

About Sean
Software developer in the Twin Cities area, passionate about software development and sailing.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: