C# : Named Arguments

One of the new features of C# 4 is named arguments. They are a pretty simple concept, but useful nonetheless. I thought I would write a quick run-down on them.

Named arguments are a language feature where you can specify the name of an argument when calling a method.

This can be a great way to clear up the intent of some method calls. I find it particularly helpful when working with bool expressions.

Here a quick sample to show what I mean :

    public void Sort(bool ascending)
    {
        // fictitious method
    }

    public void Foo()
    {
        // without named arguments
        Sort(true);

        // with named arguments
        Sort(ascending: true);
    }

The version with the named arguments is much more explicit. In the first one you are left wondering what the parameter does and may have to bring up Visual Studio’s parameter info tooltip. Named arguments are a powerful tool to write self-documenting code.

I use them not only when calling methods I wrote but also when calling methods from the framework or third-party libraries.

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