When To Use IEquatable And Why

后端 未结 5 800
天命终不由人
天命终不由人 2020-12-07 17:31

What does IEquatable buy you, exactly? The only reason I can see it being useful is when creating a generic type and forcing users to implement and write a good equ

5条回答
  •  自闭症患者
    2020-12-07 18:03

    I'm amazed that the most important reason is not mentioned here.

    IEquatable<> was introduced mainly for structs for two reasons:

    1. For value types (read structs) the non-generic Equals(object) requires boxing. IEquatable<> lets a structure implement a strongly typed Equals method so that no boxing is required.

    2. For structs, the default implementation of Object.Equals(Object) (which is the overridden version in System.ValueType) performs a value equality check by using reflection to compare the values of every field in the type. When an implementer overrides the virtual Equals method in a struct, the purpose is to provide a more efficient means of performing the value equality check and optionally to base the comparison on some subset of the struct's field or properties.

    Both of which improves performance.

    Reference types (read classes) don't benefit as much. The IEquatable<> implementation does let you avoid a cast from System.Object but that's a very trivial gain. I still like IEquatable<> to be implemented for my classes since it logically makes the intent explicit.

提交回复
热议问题