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

后端 未结 13 2171
清酒与你
清酒与你 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:53

    If you overload == for your custom type, and not != then it will be handled by the != operator for object != object since everything is derived from object, and this would be much different than CustomType != CustomType.

    Also the language creators probably wanted it this way to allow the most most flexibility for coders, and also so that they are not making assumptions about what you intend to do.

提交回复
热议问题