How can we declare Optional Parameters in C#.net? [duplicate]

让人想犯罪 __ 提交于 2019-12-21 07:15:30

问题


I am using a method for doing some action, i want the method to be written only once by using Optional Parameters in C#, other than Method Overloading is there any?


回答1:


New to visual studio 2010

named and optional arguments

for example

public void ExampleMethod(int required, string optionalstr = "default string",
int optionalint = 10)
{
}



回答2:


Have a look at following code

Library to use

using System.Runtime.InteropServices;

Function declaration

private void SampleFunction([Optional]string optionalVar, string strVar)
{
}

And while giving call to function you can do like this

SampleFunction(optionalVar: "someValue","otherValue");

OR

SampleFunction("otherValue");

Reply if it helps.!:)




回答3:


Yes, use optional parameters (introduced in C# 4).

public void ExampleMethod(int required, string optionalstr = "default string",
    int optionalint = 10)

When you provide a default value to a formal parameter, it becomes optional.

For prior versions, overloads are the only option.




回答4:


They have been introduced in C# 2010 (that is generally VS2010 with Framework 4.0). See Named and Optional Arguments (C# Programming Guide).

In previous C# versions you're stuck with overloads (or param arrays).




回答5:


If you use C# 4.0 it is.

You can then define your method like this:

public void Foo( int a = 3, int b = 5 ){
  //at this point, if the method was called without parameters, a will be 3 and b will be 5.
}


来源:https://stackoverflow.com/questions/5116625/how-can-we-declare-optional-parameters-in-c-net

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