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

后端 未结 11 760
孤街浪徒
孤街浪徒 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:23

    One step further from Joshua Shannon's nice answer. Now with preventing boxing/unboxing:

    public static class NullableEx
    {
        public static bool IsNullOrDefault(this T? value)
            where T : struct
        {
            return EqualityComparer.Default.Equals(value.GetValueOrDefault(), default(T));
        }
    }
    

提交回复
热议问题