Does null-coalescence operator match empty string?

2.6k views Asked by At

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.

1

There are 1 answers

0
Jon Skeet On BEST ANSWER

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.