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()
, whereValType
is a value type, such as anenum
or astruct
;an expression of the form
default(ValType)
, whereValType
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