Anton
Anton

Reputation: 4584

Optional Specification of some C# Optional Parameters

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?

Upvotes: 5

Views: 253

Answers (2)

Brian R. Bondy
Brian R. Bondy

Reputation: 347196

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);
    }

Upvotes: 2

Ian Mercer
Ian Mercer

Reputation: 39277

Take a look at named parameters.

    SomeMethod(bar: false);

Upvotes: 10

Related Questions