简体   繁体   中英

Optional Arguments or Named Arguments initialized to null? C#

I came across an example similar to this:

public Dictionary<string, object> generate(
  string elementId,
  Dictionary<string, object> additionalAttributes = null)
{
.... method body
}

Why would the dictionary passed as parameter be initiated to null? I haven't seen such construct. Does it have to do something with an optional parameter?

I can't speak to your first question, but the answer to your second question is yes. This is an optional parameter. C# only allows optional reference-type parameters to take a default value of null , except for string, which can take any constant string value, I believe.

Ref: MSDN

I use that to save time writing functions overloading. For example, instead of overloading two functions:

void SameFunctionName(Parameter1){ .. }
void SameFunctionName(Parameter1, Parameter2){ .. }
// maybe additional function body with three parameters .. etc

I just write one using this case:

void MyFunction(Parameter1, Parameter2 = null){ .. }

So, a small if statement inside my function would check if Parameter2 is null or not, to then make decisions. All in one function body.

and the function call for this case would work in both cases:

MyFunction(Parameter1); // This is a valid syntax
MyFunction(Parameter1, Parameter2); // This is a valid syntax

可选参数(例如您在示例中使用的参数)只能设置为常量值,这意味着您不能使用任何引用值(即Dictionary),因为null是唯一可以初始化可选值的值字典类型的变量,如果该方法使用的是int或string等值类型,则可以为可选参数初始化一个值,否则必须为null

Yes it saves time if you are using Function Overloading For example this can be avoided

Void Main()
        {
          fun1(11);
          fun1(12,13);
        }

    public fun1(int i )
    {
    Print(i);
    }

    public fun1(int i ,int j)
    {
    Print(i+j);
    }

This can be avoided by Code below and it also saves time and space

Void Main()
{
fun1(12);
}

public fun1(int i ,int j = NULL)
{
if(j==NULL)
  Print(i);
else
Print(i+j);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM