public void MyMethod(firstParameter: firstValue, secondParameter: secondValue)
This lets you call the method with parameters in a different order, and also helps to facilitate optional parameters. Aside from these benefits, I've come to like using them to improve code clarity, particularly in unit tests.
Lets say you have a method like this one:
public decimal CalculateFuelCostPerKm(double kilometresTravelled, double litresInFuelTank, decimal costToFillTank)
If you were to call that method, you might do something like this:
CalculateCostPerKm(500D, 60D, 72.58M);
However if you are reading that and don't know the parameters, you're going to have to dive deeper to understand it. A way to improve it might be:
var kilometresTravelled = 500D;
var litresInFuelTank = 60D;
var costToFillTank = 72.58M;
CalculateCostPerKm(kilometresTravelled, litresInFuelTank, costToFillTank);
Which is much clearer, but is a fair bit of effort. But with C# named parameters you can do this:
CalculateCostPerKm(kilometresTravelled: 500D, litresInFuelTank: 60D, costToFillTank: 72.58M);
Simple to do, and clear to read. In fact, this is probably one of the rare situations where C# being written
more like Objective-C is a good thing. Take this example for creating an alert dialog in the iOS SDK:
- (id)initWithTitle:(NSString *)title message:(NSString *)message delegate:(id)delegate cancelButtonTitle:(NSString*)cancelButtonTitle otherButtonTitles:(NSString *)otherButtonTitles, ...
Which you would call like:
[[UIAlertView alloc] initWithTitle:@"Error" message:@"You stuffed up" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];
Or in C# you might do something like this (ignoring the delegate business):
UIAlertView.InitWithTitle("Error", "You stuffed up", myDelegate, "OK", null);
As you can see, the verbose nature of Objective-C makes for clearer code in this instance, however, we could write the C# method like:
UIAlertView.InitWithTitle(title: "Error", message: "You stuffed up", delegate: myDelegate, cancelButtonTitle: "OK", otherButtonTitles: null);
Which makes it just as clear.
I've found this technique particularly useful in unit tests, which often tend towards using constant values. For instance I might often have a method to setup a certain state in my stubs where I take in the important parameters required, this technique makes this much easier to read.
I’d love to hear your thoughts on this technique, either in the comments on this post or via Twitter (@rodh257)