?? Coalesce for empty string?

后端 未结 10 1207
甜味超标
甜味超标 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:05

    I know this is an old question - but I was looking for an answer and none of the above fit my need as well as what I ended up using:

    private static string Coalesce(params string[] strings)
    {
        return strings.FirstOrDefault(s => !string.IsNullOrEmpty(s));
    }
    

    Usage:

    string result = Coalesce(s.SiteNumber, s.AltSiteNumber, "No Number");
    

    EDIT: An even more compact way of writing this function would be:

    static string Coalesce(params string[] strings) => strings.FirstOrDefault(s => !string.IsNullOrEmpty(s));
    

提交回复
热议问题