How to skip optional parameters in C#?
Example:
public int foo(int x, int optionalY = 1, int optionalZ = 2) { ... }
I'd like to call it like this:
int returnVal = foo(5,,8);
In other words, I want to provide x
and z
, but I want to use the default for Y
, optionalY = 1.
Visual Studio does not like the ,,
Please help.
If this is C# 4.0, you can use named arguments feature:
foo(x: 5, optionalZ: 8);
See this blog for more information.
In C# 4.0 you can name the arguments occurring after skipped defaults like this:
int returnVal = foo(5, optionalZ: 8);
This is called as named arguments. Several others languages provide this feature, and it's common form them to use the syntax foo(5, optionalZ=8)
instead, which is useful to know when reading code in other languages.