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.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top