简体   繁体   中英

C# - A more efficient ternary operator

I was making a program in which I want to check if a string is equal to "" , and if it isn't use it, but if it is, use the default value. I know I can do string != "" ? string : "default value" string != "" ? string : "default value" , however, I feel like this is inefficient, as I keep typing out string . Of course, writing out string is no problem for me, but, if in another project, I have to reference a string with a long package name, it would be a little more annoying.

At the moment there is no operator that can do what you want.

But there is actually a proposal for a "Default-or-Empty Coalesce operator", here:

https://github.com/dotnet/csharplang/issues/183

The best you can do at the moment is to declare an extension method like this:

    public static string NullIfEmpty(this string str)
    {
        return string.IsNullOrEmpty(str) ? null : str;
    }

and use it like this:

var foo = yourString.NullIfEmpty() ?? "default value";

According to DavidG's option and helpful link, you could use this extension function.

public static string IfEmpty(this string str, string alternate)
{
    return str?.Length == 0 ? str : alternate;
}

(This will return the alternate string even if the 'str' is null)

And use as mystring.IfEmpty("something else")

Source: What is the difference between String.Empty and "" (empty string)? .

Also you don't need to reference a really long string.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM