C#-How to use empty List as optional parameter

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.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)