C#-How to use empty List<string> as optional parameter
Can somebody provide a example of this?
I have tried null
,string.Empty
and object initialization b开发者_如何转开发ut they don't work since default value has to be constant at compile time
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.
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>();
}
You can simplify this even further to:
void DoSomething(List<string> lst = default)
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());
}
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
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();
...
}
I like it this way, it is more readable then ??=
if (param == null) param = new();
private void test(params object[] params)
{
}
精彩评论