I write this code :
private bool test(List<string> Lst = new List<string>() { "ID" })
{
return false;
}
i want to set default value for "Lst" but has an error from "new" key word. any idea?
Currently it's not possible in C# to initialize parameters with new objects or classes.
You can leave default value as null and in your method create your class instance:
private bool test(List<string> Lst = null)
{
if(Lst == null)
{
Lst = new List<string> { "ID" };
}
return false;
}
In C# 8 we could shorten this kind of expressions with the new null conditional operator:
private bool test(List<string> Lst = null)
{
Lst ??= new List<string> { "ID" };
return false;
}
You can set the default to null and then set this to your desired default in the first line
private bool test(List<string> Lst = null)
{
List<string> tempList; // give me a name
if(Lst == null)
tempList = new List<string>() { "ID" };
else
tempList = Lst;
return false;
}
Now you can use tempList in your desired way
This is not possible. See the MSDN docs for allowed values.
A possible alternative is to use overrides and/or a default value of null instead. Use either:
// Override
private bool test()
{
return test(new List<string>() { "ID" });
}
// default of null
private bool test(List<string> Lst = null)
{
if (Lst == null) {
Lst = new List<string>() { "ID" };
}
return false;
}
Not quite sure what you want to achieve, but you can use ref to initialize the list if it is null.
void SetDefault(ref List<string> list)
{
if(list == null)
{
list = new List<string>();
}
}
default(List<string>)instead.List<string> Lst = default(List<string>)