How to compare nullable types?
Posted
by David_001
on Stack Overflow
See other posts from Stack Overflow
or by David_001
Published on 2010-02-26T12:53:45Z
Indexed on
2010/04/01
2:03 UTC
Read the original article
Hit count: 953
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.
© Stack Overflow or respective owner