?? Coalesce for empty string?

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

    I simply use a NullIfEmpty extension method which will always return null if the string is empty allowing ?? (Null Coalescing Operator) to be used as normal.

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

    This then allows ?? to be used as normal and makes chaining easy to read.

    string string1 = string2.NullIfEmpty() ?? string3.NullIfEmpty() ?? string4;
    

提交回复
热议问题