Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check null in C# 6 with default value

Tags:

c#

c#-6.0

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?

like image 460
Miguel Moura Avatar asked Nov 30 '25 14:11

Miguel Moura


2 Answers

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]);
like image 185
Igor Avatar answered Dec 02 '25 05:12

Igor


The best alternative would be to check for null before joining the strings:

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

Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!