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

Solution 1:

Just use the null coalescing operator and an instance of empty List<string>

public void Process(string param1, List<string> param2 = null) 
{
    param2 = param2 ?? new List<string>();

    // or starting with C# 8
    param2 ??= new List<string>();
}

The problem with this is that if "param2" is null and you assign a new reference then it wouldn't be accessible in the calling context.

Solution 2:

You may also do the following using default which IS a compile-time-constant (null in the case of a List<T>):

void DoSomething(List<string> lst = default(List<string>)) 
{
    if (lst == default(List<string>)) lst = new List<string>();
}

Solution 3:

It is impossible. You should use method overloading instead.

public static void MyMethod(int x, List<string> y) { }
public static void MyMethod(int x)
{
    MyMethod(x, Enumerable<string>.Empty());
}

Solution 4:

    private void test(List<string> optional = null)
    {

    }

sorry about the string instead of list. Null works fine for me on 4.0, i am using visual studio 2010