optional array Parameter in C#

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'...
}

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

Tags:

C#

C# 4.0