Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# functions and optional parameters

Tags:

c#

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 ?

like image 485
BuZz Avatar asked Jan 26 '26 12:01

BuZz


2 Answers

Try:

f(11, c: 33)

And take a look at the documentation

like image 173
srgerg Avatar answered Jan 29 '26 13:01

srgerg


You can prefix the parameter with the argument name:

f(1, c:3);
like image 37
Jason Avatar answered Jan 29 '26 13:01

Jason



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!