BuZz
BuZz

Reputation: 17445

C# functions and optional parameters

I know that in C# it is possible to define optional parameters. My question is directed at how flexible this is.

Let f be a function as below, with a mandatory and b, c optional :

class Test {
   public void f(int a, int b = 2, int c = 3) {
      //...
   }
}

Now, I know I can call the function in the following ways :

f(1) -> a equals 1, b equals 2, c equals 3

f(11,22) -> a equals 11, b equals 22, c equals 3

f(11,22,33) -> a equals 11, b equals 22, c equals 33

How do I do to not specify b, but a and c ?

Upvotes: 3

Views: 2025

Answers (5)

DaveVentura
DaveVentura

Reputation: 760

Another possibility would be to define the method with other parameters and call the original one with them using this syntax:

public void f(int a, int c = 3) => f(a, 2, c)

More comfortable usability if you call it, but gets fiddly to define if you have more than 2 optional parameters .

Upvotes: 0

Mithrandir
Mithrandir

Reputation: 25337

You use named parameters:

f( a:100, c:300);

Upvotes: 0

Rob Levine
Rob Levine

Reputation: 41298

Using named arguments:

f(a: 5, c: 6);

Although, strictly speaking in my example, you don't have to qualify the a:

f(5, c: 6);

Upvotes: 2

Jason
Jason

Reputation: 1226

You can prefix the parameter with the argument name:

f(1, c:3);

Upvotes: 2

srgerg
srgerg

Reputation: 19329

Try:

f(11, c: 33)

And take a look at the documentation

Upvotes: 7

Related Questions