C# 4.0 Named Arguments – example usage

Posted by – August 24, 2010

One of the new features introduced in C# 4.0 were named arguments. There was a lot of discussion in the Internet about them and theirs pros and cons. Of course named arguments can be abused like any other part of C# but I think that when used wisely are able to make your code more readable and easier to understand without the knowledge what is hidden behind the scene. Few days ago I was working on integration tests for REST API exposed by a startup I am working on with my team. Each test required some “execution context” and a way to inform “infrastructure” that after execution whole environment should be cleaned up (e.g. database). Because I use NUnit as a runner the first idea that came to my mind was to utilize [SetUp] and [TearDown] methods. But after some prototyping I realized that the solution is hard to understand and obfuscates the tests. Next day after short chat with @lesnikowski new idea popped into my mind: I can create “execution context” with lambdas and named arguments! The example below shows how I have changed the idea into real code.

[Test]
public void Add_WhenInvokedShouldAddNewExternalAudioFolder()
{
    Execute(test: () =>
    {
        var json = WebApiClient.ExternalAudioFolder.Add("My folder", "My description");
        var message = json.DeserializeJson<AddMessage>();

        Assert.That(message.Result, Is.EqualTo(Message.Success));
    },
    inContextOf: Account.Basic,
    cleanUpAfter: true);
}

What do you think about the code above? Do you have any additional ideas how to improve readability of this “execution context”?

Hey, keep in touch!! Follow me on Twitter, @marcinobel or subscribe to this blog.
0 Comments on C# 4.0 Named Arguments – example usage

Respond | Trackback

Respond

Comments

Comments