简体   繁体   中英

Check null in C# 6 with default value

I am using C# 6 and I have the following:

public class Information {
  public String[] Keywords { get; set; }
}

Information information = new Information {
  Keywords = new String[] { "A", "B" };
}

String keywords = String.Join(",", information?.Keywords ?? String.Empty);

I am checking if information is null (in my real code it can be). If it is than join a String.Empty since String.Join gives an error when trying to join null. If it is not null then just join information.Keywords.

However, I get this error:

Operator '??' cannot be applied to operands of type 'string[]' and 'string'

I was looking on a few blogs and supposedly this would work.

Am I missing something?

What is the best alternative to do this check and join the string in one line?

As the types must match on either side of the ?? (null-coalescing) operator you should pass a string array, in this case you could pass an empty string array.

String keywords = String.Join(",", information?.Keywords ?? new string[0]);

最好的替代方法是加入字符串之前检查null:

var keywords = information?.Keywords == null ? "" : string.Join(",", information.Keywords);

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM