views:

71

answers:

2

Suppose you have a method with the following signature:

public void SomeMethod(bool foo = false, bool bar = true) { /* ... */ }

When calling this method, is there a way to specify a value for bar and not foo? It would look something like...

SomeMethod(_, false);

... which would translate to...

SometMethod(false, false);

... at compile-time. Is this possible?

+2  A: 

With C#4 you can specify parameters to functions in 2 ways:

  1. Positional: What was always supported
  2. Named: You can specify the name of each parameter and put them in any order

With positional parameters there is no way to specify only the 2nd default parameter. With named parameters there is. Simply omit the first named parameter.

Here is an example:

    static void test(bool f1 = false, bool f2 = false)
    {
        //f1 == false and f2 == true
    }

    static void Main(string[] args)
    {
        test(f2: true);
    }
Brian R. Bondy
+9  A: 

Take a look at named parameters.

    SomeMethod(bar: false);
Hightechrider
Good resource here: http://geekswithblogs.net/michelotti/archive/2009/01/22/c-4.0-named-parameters-for-better-code-quality.aspx
Bob Kaufman
Perfect, thanks!
Anton