?? Coalesce for empty string?

后端 未结 10 1206
甜味超标
甜味超标 2020-12-12 18:30

Something I find myself doing more and more is checking a string for empty (as in \"\" or null) and a conditional operator.

A current example:



        
10条回答
  •  旧时难觅i
    2020-12-12 19:21

    I like the brevity of the following extension method QQQ for this, though of course an operator like? would be better. But we can 1 up this by allowing not just two but three string option values to be compared, which one encounters the need to handle every now and then (see second function below).

    #region QQ
    
    [DebuggerStepThrough]
    public static string QQQ(this string str, string value2)
    {
        return (str != null && str.Length > 0)
            ? str
            : value2;
    }
    
    [DebuggerStepThrough]
    public static string QQQ(this string str, string value2, string value3)
    {
        return (str != null && str.Length > 0)
            ? str
            : (value2 != null && value2.Length > 0)
                ? value2
                : value3;
    }
    
    
    // Following is only two QQ, just checks null, but allows more than 1 string unlike ?? can do:
    
    [DebuggerStepThrough]
    public static string QQ(this string str, string value2, string value3)
    {
        return (str != null)
            ? str
            : (value2 != null)
                ? value2
                : value3;
    }
    
    #endregion
    

提交回复
热议问题