How to skip optional parameters in C#?

C#Optional Parameters

C# Problem Overview


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.

C# Solutions


Solution 1 - C#

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

foo(x: 5, optionalZ: 8); 

See this blog for more information.

Solution 2 - C#

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.

Solution 3 - C#

Another dynamic way to supply parameters of your choise is to implement your method(s) in a class and supply named parameters to the class constructor. Why not even add calls to methods on same line of code as mentioned here : https://stackoverflow.com/questions/12056639/how-to-define-named-parameters-c-sharp

>var p = new PersonInfo { Name = "Peter", Age = 15 }.BuildPerson();

Solution 4 - C#

This is a late answer, but for the people who get into this. One could also use Overloads,that uses the same name as the method/function, but with a different set of parameters.

ea

int SummAll (int a=0, int b=1, int c=2)
{return a+b+c;}

int SumAll (int a=0;int c=10) //skipping B 
{return a+c; }

This pattern equals how with intellicense we can browse through variations of functions.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionIan DavisView Question on Stackoverflow
Solution 1 - C#Josiah RuddellView Answer on Stackoverflow
Solution 2 - C#moinudinView Answer on Stackoverflow
Solution 3 - C#tofoView Answer on Stackoverflow
Solution 4 - C#PeterView Answer on Stackoverflow