How to compare nullable types?

后端 未结 8 1510
夕颜
夕颜 2021-01-31 13:32

I have a few places where I need to compare 2 (nullable) values, to see if they\'re the same.

I think there should be something in the framework to support this, but can

相关标签:
8条回答
  • 2021-01-31 13:57

    Nullable.Equals<T>?

    0 讨论(0)
  • 2021-01-31 13:57
    if (x.Equals(y)) 
    
    0 讨论(0)
  • 2021-01-31 13:59
    (x?? 0).Equals(y)
    

    will handle null as well as equals.

    0 讨论(0)
  • 2021-01-31 14:05

    Just use ==, or .Equals().

    0 讨论(0)
  • 2021-01-31 14:08

    I wanted to find how to compare two nullable int on C#, but I always get this link after search, so if someone needs to compare exactly two nullable int, then this can be helpful

    a.GetValueOrDefault(int.MinValue).CompareTo(b.GetValueOrDefault(long.MinValue));

    0 讨论(0)
  • 2021-01-31 14:13

    You can use the static Equals method on System.Object:

    var equal = object.Equals(objA, objB);
    
    0 讨论(0)
提交回复
热议问题