Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

c#-4.0

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

like image 855
Pavan Keerthi Avatar asked Aug 04 '11 19:08

Pavan Keerthi


2 Answers

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.

like image 124
Vasea Avatar answered Sep 26 '22 06:09

Vasea


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>(); } 
like image 42
MakePeaceGreatAgain Avatar answered Sep 23 '22 06:09

MakePeaceGreatAgain