Does the null coalescence operator match an empty string?

I have a very simple question with C #: are the following statements equal when working with an empty string?

s ?? "default"; 

or

 (!string.IsNullOrEmpty(s)) ? s : "default"; 

I think: with string.Empty!=null the coalescence operator can set the result of the first statement to an empty value when what I really want is the second. Since string is somehow special (== and! = Overloaded to compare values), I just wanted to ask C # experts to make sure.

Thanks.

+4
source share
1 answer

Yes, you are right - they are not the same, and as you indicated.

If you are not comfortable with the first form, you can write the extension:

 public static string DefaultIfNullOrEmpty(this string x, string defaultValue) { return string.IsNullOrEmpty(x) ? defaultValue : x; } 

then you can simply write:

 s.DefaultIfNullOrEmpty("default") 

in your main code.

+15
source

Source: https://habr.com/ru/post/1338032/


All Articles