How to skip optional parameters in C#?

三世轮回 提交于 2019-11-29 05:24:35
Josiah Ruddell

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.

tofo

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 : How to define named Parameters C#

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

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!