Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does null-coalescence operator match empty string?

I have a very simple C# question: aren't the following statements equal when dealing with an empty string?

s ?? "default";

or

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

I think: since string.Empty!=null, the coalescence operator may set the result of the first statement to an empty value when what I really want is the second. Since string is someway special (== and != are overloaded to value-compare) I just wanted to ask to C# experts to make sure.

Thank you.

like image 635
usr-local-ΕΨΗΕΛΩΝ Avatar asked Dec 06 '22 23:12

usr-local-ΕΨΗΕΛΩΝ


1 Answers

Yes, you're right - they're not the same, and in the way that you specified.

If you're not happy with the first form, you could write an extension of:

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

then you can just write:

s.DefaultIfNullOrEmpty("default")

in your main code.

like image 178
Jon Skeet Avatar answered Dec 27 '22 10:12

Jon Skeet