?? Coalesce for empty string?

后端 未结 10 1186
甜味超标
甜味超标 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条回答
  •  既然无缘
    2020-12-12 19:24

    I have a couple of utility extensions that I like to use:

    public static string OrDefault(this string str, string @default = default(string))
    {
        return string.IsNullOrEmpty(str) ? @default : str;
    }
    
    public static object OrDefault(this string str, object @default)
    {
        return string.IsNullOrEmpty(str) ? @default : str;
    }
    

    Edit: Inspired by sfsr's answer, I'll be adding this variant to my toolbox from now on:

    public static string Coalesce(this string str, params string[] strings)
    {
        return (new[] {str})
            .Concat(strings)
            .FirstOrDefault(s => !string.IsNullOrEmpty(s));
    }
    

提交回复
热议问题