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

后端 未结 11 740
孤街浪徒
孤街浪徒 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:29
    class Item{  
     bool IsNullOrZero{ get{return ((this.Rate ?? 0) == 0);}}
    }
    
    0 讨论(0)
  • 2020-11-30 23:34

    I like if ((item.Rate ?? 0) == 0) { }

    Update 1:

    You could also define an extension method like:

    public static bool IsNullOrValue(this double? value, double valueToCheck)
    {
        return (value??valueToCheck) == valueToCheck;
    }
    

    And use it like this:

    if(item.IsNullOrValue(0)){} // but you don't get much from it

    0 讨论(0)
  • 2020-11-30 23:39

    I agree with using the ?? operator.

    If you're dealing with strings use if(String.IsNullOrEmpty(myStr))

    0 讨论(0)
  • 2020-11-30 23:39

    You code sample will fail. If obj is null then the obj.ToString() will result in a null reference exception. I'd short cut the process and check for a null obj at the start of your helper function. As to your actual question, what's the type you're checking for null or zero? On String there's a great IsNullOrEmpty function, seems to me this would be a great use of extension methods to implement an IsNullOrZero method on the int? type.

    Edit: Remember, the '?' is just compiler sugar for the INullable type, so you could probably take an INullable as the parm and then jsut compare it to null (parm == null) and if not null compare to zero.

    0 讨论(0)
  • 2020-11-30 23:42

    Using generics:

    static bool IsNullOrDefault<T>(T value)
    {
        return object.Equals(value, default(T));
    }
    
    //...
    double d = 0;
    IsNullOrDefault(d); // true
    MyClass c = null;
    IsNullOrDefault(c); // true
    

    If T it's a reference type, value will be compared with null ( default(T) ), otherwise, if T is a value type, let's say double, default(t) is 0d, for bool is false, for char is '\0' and so on...

    0 讨论(0)
提交回复
热议问题