'How to compare nullable types?
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't find anything, so instead have the following:
public static bool IsDifferentTo(this bool? x, bool? y)
{
return (x.HasValue != y.HasValue) ? true : x.HasValue && x.Value != y.Value;
}
Then, within code I have if (x.IsDifferentTo(y)) ...
I then have similar methods for nullable ints, nullable doubles etc.
Is there not an easier way to see if two nullable types are the same?
Update:
Turns out that the reason this method existed was because the code has been converted from VB.Net, where Nothing = Nothing returns false (compare to C# where null == null returns true). The VB.Net code should have used .Equals... instead.
Solution 1:[1]
Solution 2:[2]
if (x.Equals(y))
Solution 3:[3]
You can use the static Equals method on System.Object:
var equal = object.Equals(objA, objB);
Solution 4:[4]
Solution 5:[5]
Just use ==, or .Equals().
Solution 6:[6]
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));
Solution 7:[7]
(x?? 0).Equals(y)
will handle null as well as equals.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Anton Gogolev |
| Solution 2 | Kashif |
| Solution 3 | Mark Seemann |
| Solution 4 | Lucero |
| Solution 5 | Lucero |
| Solution 6 | hdd42 |
| Solution 7 | Zoe stands with Ukraine |
