Increased readability with C# 4 named arguments

If you've read ScottGu's recent post, you'll know that C# 4 will include support for optional parameters and named arguments.

Now, this enables some interesting new scenarios for usability, but the thing I'm concerned about here is something very simple: not to make the code more terse or elegant, but simply more readable.

I think code is readable when it's simple to understand, and where names are self-explanatory. Some APIs lend themselves well to writing this code, while others make this a bit trickier.

A classic example is a method with bool parameters. At the call site, they frequently make it very hard to figure out what they mean. For example, let's say I create a stream with this code:

StreamWriter writer = new StreamWriter(@"C:\text.txt");

It's pretty obvious that the stream is going to write to a file called C:\text.txt. How about this, though?

StreamWriter writer = new StreamWriter(@"C:\text.txt", true);

What the heck does true mean? Is it an 'overwrite' file, does it affect the encoding, does it affect file ownership, or what? Without looking at the API, it's very hard to tell. With Intellisense at least you can put the cursor on the true keyword and bring up the signature, which shows the argument name, but with C# 4 we can do a lot better:

StreamWriter writer = new StreamWriter(@"C:\text.txt", append: true);

Now you can see the effect of that true on the signature, without having to look up the documentation. You still need docs to write down the fine print (what happens if the file doesn't yet exists, or the directory doesn't exist, etc), but you've just improved your code readability quite a bit.

And given how many more times you read code compared to writing code, I'm all for this.