How to skip optional parameters in C#?

Ian Davis picture Ian Davis · Jan 7, 2011 · Viewed 15.7k times · Source

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.

Answer

Josiah Ruddell picture Josiah Ruddell · Jan 7, 2011

If this is C# 4.0, you can use named arguments feature:

foo(x: 5, optionalZ: 8); 

See this blog for more information.