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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With