C # Explicit Equality Operator Implementation Needed

I see that I explicitly implement Equals and GetHashCode for my objects.

But I wonder if it makes sense to explicitly implement the == and! =, for example:

public static bool operator ==(Salutation left, Salutation right) { return Equals(left, right); } 

Does C # allow you to use the Equals method when calling ==?

+7
c #
source share
2 answers

Indeed, it makes sense to redefine the equality operator along with Equals . It is really very desirable.

Microsoft has published the official Implementation Guide for Equals and the Equality Operator (==) on MSDN. I would definitely go for recommended practices there. Two main points:

  • Inject the GetHashCode method whenever you implement the Equals method. This keeps the equal and GetHashCode synchronized.
  • Override the Equals method whenever you execute the equality operator (==), and force them to do the same. This allows you to use infrastructure code like Hashtable and ArrayList, which use the Equals method, to behave the same as user code written using the equality operator.

John Skeet also wrote a useful MSDN blog post on this subject, which briefly describes the operation of the Equals operator and == on types of links / values.

The most important parts are listed below:

The Equals method is just a virtual one, defined in System.Object, and is overridden by which classes are chosen for this. The == operator is an operator that can be overloaded with classes, but usually an identity.

For reference types, where == was not overloaded, it compares two references to the same object - this is exactly what the Equals implementation in System.Object does.

Value types do not provide overloads for == by default. However, most types of values ​​provided by the framework provide their own overload. The standard Equals implementation for a value type is provided by ValueType, and uses reflection to make a comparison, which makes it significantly slower than a typical implementation would be. This implementation also calls for equal pairs of links within the two compared values.

+8
source share

If you don't overload it, == just checks for reference equality: do both sides refer to the same object?

If you need equal values ​​(do different objects have the same value on both sides?), You can overload the statement. At the moment, you almost always want to overload .Equals () and .GetHashCode (), and also have your overload call ==. Equals ().

+2
source share

All Articles