-2

If I am using a method with multiple optional parameters, how can I call the method without specifying only one of the parameters, letting it use its default value?

Say I have method Foo with multiple optional parameters:

void Foo(string a, int b = 5, bool c = false, float d = 0.5f);

And I want to call this method while giving params b and d a specific value, while not caring about c and giving it its default value:

Foo("Hello World", 6, /*default*/, 1.9f);

What do I write instead of /*default*/ to make this happen?

Note: I found this question elsewhere, closed as duplicate, without an answer, while the answer in the linked duplicate gave no solution to the problem I am proposing. Please consider this question correctly before dismissing it.

DMX David Cardinal
  • 599
  • 2
  • 7
  • 19
  • 1
    See [Named and optional arguments](https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/named-and-optional-arguments) – John Wu May 25 '20 at 19:07
  • The comment above gives you everything you need. What question did you find that was supposedly falsely closed as duplicate? – Joelius May 25 '20 at 19:13
  • @Joelius Yes, I can see it and the answer from Yuriy confirms it. I had visibly missed the small passage that mentionned the notion I was looking for. [This](https://stackoverflow.com/questions/58213968/c-how-can-you-skip-former-arguments-when-using-a-function-if-there-are-multipl) is the question where no answer was given apart from replies from the comments. At least my question has an actual answer now, even if it gets closed too, for future people looking for this information. – DMX David Cardinal May 25 '20 at 19:23

1 Answers1

4
Foo("Hello World", b: 6, d: 1.9f);
Yuriy Faktorovich
  • 67,283
  • 14
  • 105
  • 142