简体   繁体   中英

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.

C# supports "lifted" operators, so if the type ( bool? in this case) is known at compile you should just be able to use:

return x != y;

If you need generics, then EqualityComparer<T>.Default is your friend:

return !EqualityComparer<T>.Default.Equals(x,y);

Note, however, that both of these approaches use the " null == null " approach (contrast to ANSI SQL). If you need " null != null " then you'll have to test that separately:

return x == null || x != y;
if (x.Equals(y)) 

您可以在 System.Object 上使用静态Equals方法:

var equal = object.Equals(objA, objB);

只需使用==.Equals()

(x?? 0).Equals(y)

将处理 null 和 equals。

我想找到如何在 C# 上比较两个可为空的 int,但我总是在搜索后得到这个链接,所以如果有人需要比较两个可为空的 int,那么这可能会有所帮助

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM