How to compare nullable types?

后端 未结 8 1532
夕颜
夕颜 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 14:23

    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.Default is your friend:

    return !EqualityComparer.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;
    

提交回复
热议问题