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]);
The best alternative would be to check for null before joining the strings:
var keywords = information?.Keywords == null ? "" : string.Join(",", information.Keywords);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With