Nullable types: better way to check for null or zero in c#

后端 未结 11 741
孤街浪徒
孤街浪徒 2020-11-30 22:45

I\'m working on a project where i find i\'m checking for the following in many, many places:

if(item.Rate == 0 || item.Rate == null) { }

mo

11条回答
  •  情深已故
    2020-11-30 23:21

    Although I quite like the accepted answer, I think that, for completeness, this option should be mentioned as well:

    if (item.Rate.GetValueOrDefault() == 0) { }
    

    This solution

    • does not require an additional method,
    • is faster than all the other options, since GetValueOrDefault is a single field read operation¹ and
    • reads easier than ((item.Rate ?? 0) == 0) (this might be a matter of taste, though).

    ¹ This should not influence your decision, though, since these kinds of micro-optimization are unlikely to make any difference.

提交回复
热议问题