optional array Parameter in C# [duplicate]

2020-08-09 08:19发布

问题:

This question already has answers here:
Closed 8 years ago.

Possible Duplicate:
passing an empty array as default value of optional parameter in c#

I have a method that looks like below. Currently, the parameter tags is NOT optional

void MyMethod(string[] tags=null)
{
   tags= tags ?? new string[0];
   /*More codes*/
}

I want to make parameter tags optional, as per c# , to make a parameter optional you can set a default value in method signature. I tried the following hacks but none worked.

Code that didn't work - 1

void MyMethod(string[] tags=new string[0]){}

Code that didn't work - 2

void MyMethod(string[] tags={}){}

Please suggest what I am missing.


I have already seen this question:

Passing an empty array as default value of an optional parameter

回答1:

The documentation for optional arguments says:

A default value must be one of the following types of expressions:

  • a constant expression;

  • an expression of the form new ValType(), where ValType is a value type, such as an enum or a struct;

  • an expression of the form default(ValType), where ValType is a value type.

Since new string[0] is neither a constant expression nor a new statement followed by a value type, it cannot be used as a default argument value.

The first code excerpt in your question is indeed a good workaround:

void MyMethod(string[] tags = null)
{
   tags = tags ?? new string[0];
   // Now do something with 'tags'...
}


回答2:

not sure if i am getting it right this works.

  static void Main(string[] args)
        {
                TestMe();

        }


private static void TestMe(string[] param = null)
    {
        if (param == null)
        { 
            Console.WriteLine("its empty");
        }
    }

also the value of param has to be compile time constant