Why must we define both == and != in C#?

后端 未结 13 2223
清酒与你
清酒与你 2020-11-27 08:55

The C# compiler requires that whenever a custom type defines operator ==, it must also define != (see here).

Why?

I\'m curious to k

13条回答
  •  误落风尘
    2020-11-27 09:57

    If you look at implementations of overloads of == and != in the .net source, they often don't implement != as !(left == right). They implement it fully (like ==) with negated logic. For example, DateTime implements == as

    return d1.InternalTicks == d2.InternalTicks;
    

    and != as

    return d1.InternalTicks != d2.InternalTicks;
    

    If you (or the compiler if it did it implicitly) were to implement != as

    return !(d1==d2);
    

    then you are making an assumption about the internal implementation of == and != in the things your class is referencing. Avoiding that assumption may be the philosophy behind their decision.

提交回复
热议问题