?? Coalesce for empty string?

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

    C# already lets us substitute values for null with ??. So all we need is an extension that converts an empty string to null, and then we use it like this:

    s.SiteNumber.NullIfEmpty() ?? "No Number";
    

    Extension class:

    public static class StringExtensions
    {
        public static string NullIfEmpty(this string s)
        {
            return string.IsNullOrEmpty(s) ? null : s;
        }
        public static string NullIfWhiteSpace(this string s)
        {
            return string.IsNullOrWhiteSpace(s) ? null : s;
        }
    }
    

提交回复
热议问题