C#-How to use empty List<string> as optional parameter

Viewed 93125

Can somebody provide a example of this?

I have tried null,string.Empty and object initialization but they don't work since default value has to be constant at compile time

7 Answers

I like it this way, it is more readable then ??=

if (param == null) param = new();

As others mentioned you assign null to the optional parameter, in newer versions when using <Nullable>enable</Nullable> you need to mark the parameter with the nullable annotation (?) and assign a null value to it, otherwise it will cause error CS8625 - Cannot convert null literal to non-nullable reference type.

void DoSomething(string param, List<string>? optional = null)
{
   // Check if the parameter is null, if so create empty list
   optional ??= new();

   ...
} 
private void test(params object[] params)
{

}
Related