Miguel Moura Miguel Moura -4 years ago 127
C# Question

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?

Answer Source

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]);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download