?? Coalesce for empty string?

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

    There isn't a built-in way to do this. You could make your extension method return a string or null, however, which would allow the coalescing operator to work. This would be odd, however, and I personally prefer your current approach.

    Since you're already using an extension method, why not just make one that returns the value or a default:

    string result = s.SiteNumber.ConvertNullOrEmptyTo("No Number");
    

提交回复
热议问题