Tidbits from the Pluralsight trenches

Use C# named parameters

with 2 comments

As of .NET version 4.0, C# supports named and optional arguments. This comes in really handy for distinguishing method parameters that have the same type. For example:

public interface IGenerator<T>
    T Generate(T min, T max);

It would be really easy to accidentally pass arguments to GenerateĀ in the wrong order, since they have the same type. But using named arguments, you can be a little bit more explicit, which helps reduce the chance you’ll screw up:

var n = generator.Generate(min: 0, max: 42);

I try to follow the rule that no method should take more than two arguments, so I end up using this technique most often with constructors, which often need to take a lot of parameters. But more on that in another post…

About these ads

Written by Keith Sparkjoy

June 22, 2011 at 6:03 am

Posted in Uncategorized

2 Responses

Subscribe to comments with RSS.

  1. [...] I posted about how I use C# named parameters to clarify my intent when I call a method that takes arguments of the same type. Well, here’s [...]

  2. “C# Named Parameters” Good article here

    Gaurav Agrawal

    July 16, 2011 at 10:08 am

Leave a Reply

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

You are commenting using your 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


Get every new post delivered to your Inbox.

Join 213 other followers

%d bloggers like this: