I want to set a variable to a default value if the assignment returns null or something else.
string a = GetValue();
if GetValue returns null, then I want to have a default value for variable a, how to do that in c#. Try not using if.
Thanks for the time.
使用null合并运算符。
string a = GetValue() ?? "Default";
string a = GetValue() ?? "DefaultValue";
那将是
string a = GetValue() ?? "default value";
这个怎么样?
string a = GetValue() != null ? GetValue() : "default";
string a = GetValue() == null ? string.empty : GetValue();
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.