Implementing equality can be tricky. If we follow a few simple rules we can avoid the common traps.
Let's say we have a person class that is functioning as an entity object as in the following:
- public class Person
- {
- private readonly String _Identifier;
-
- public Person(String identifier)
- {
- _Identifier = identifier;
- }
-
- public String Identifier
- {
- get
- {
- return _Identifier;
- }
- }
- }
We probably want to override equality because equality is determined by an identifier for value objects. By default, the "Equals()" method just checks to see whether the reference of two objects point to the same memory location. In the code below, the equality check will return "false" even though the two entity objects are the same.
- Person firstPerson = new Person("123-45-6789");
-
-
-
- Person secondPerson = new Person("123-45-6789");
-
- if (firstPerson.Equals(secondPerson))
- {
-
- }
The Surface Area
This is a common
modeling problem. To address it, we will first implement the IEquatable interface.
- public class Person: IEquatable
- {
- private readonly String _Identifier;
-
- public Person(String identifier)
- {
- _Identifier = identifier;
- }
-
- public String Identifier
- {
- get
- {
- return _Identifier;
- }
- }
-
- public bool Equals(Person other)
- {
- throw new NotImplementedException();
- }
- }
Next we will also override the "Equals()" method on the base class "System.Object" on which all classes in C# inherit. If we override "Equals()" we should also override "GetHashCode()".
- public class Person: IEquatable
- {
- private readonly String _Identifier;
-
- public Person(String identifier)
- {
- _Identifier = identifier;
- }
-
- public String Identifier
- {
- get
- {
- return _Identifier;
- }
- }
-
- public bool Equals(Person other)
- {
- throw new NotImplementedException();
- }
-
- public override bool Equals(object obj)
- {
- return base.Equals(obj);
- }
-
- public override int GetHashCode()
- {
- return base.GetHashCode();
- }
- }
We also have the option to override the equality operator to enable syntax like the following:
- Person firstPerson = new Person("123-45-6789");
-
-
-
- Person secondPerson = new Person("123-45-6789");
-
- if (firstPerson == secondPerson)
- {
-
- }
If we are overriding equality, we should be consistent in order to prevent defects being introduced from misunderstanding. It would be hard to make the case that the two ways to check for equality should behave differently. The argument could be made that the equality operator should not be implemented, but then it also checks for pointer references. If we have different behavior in the two ways to evaluate equality between instances, there is a high risk of defects being introduced by other programmers who will make assumptions.
Since assumptions will eventually be made either way, it is far less risky to err on the side of consistent behavior. If we override the "Equals()" method and do not implement the equality operator, false assumptions will lead to defects in the code base. If we override the "Equals()" method and also implement the equality operator, the impact of the false assumption that the equality operator is reference checking is much smaller.
Besides, if we want to check for reference equality, we should explicitly use the "ReferenceEquals()" method.
- var test1 = firstPerson == secondPerson;
- var test2 = firstPerson.Equals(secondPerson);
- Here is the surface of what we will have to implement to implement the equality operator.
-
- public class Person: IEquatable
- {
- private readonly String _Identifier;
-
- public Person(String identifier)
- {
- _Identifier = identifier;
- }
-
- public String Identifier
- {
- get
- {
- return _Identifier;
- }
- }
-
- public bool Equals(Person other)
- {
- throw new NotImplementedException();
- }
-
- public override bool Equals(object obj)
- {
- return base.Equals(obj);
- }
-
- public override int GetHashCode()
- {
- return base.GetHashCode();
- }
-
- public static Boolean operator == (Person first, Person second)
- {
- throw new NotImplementedException();
- }
-
- public static Boolean operator != (Person first, Person second)
- {
- throw new NotImplementedException();
- }
- }
Trap #1 The first problem we run into when implementing the equality operator "==" is that it is easy to inadvertently add infinite recursion.
- public static Boolean operator == (Person first, Person second) {
- if (first == null && second == null)
- {
- return true;
- }
- }
The "first" or "second" parameters could be null. So rather than using the equality operator "==" to check for reference equality, we can do it explicitly using the "ReferenceEquals()" method. If the references are the same, then it is the same instance and will have the same identifier value. If both the "first" and "second" person are null references, then we can also return "true". However, if either the "first" or "second" person is null and the other is not null, then they cannot be equal. In order to keep our code
dry, we'll just check if the "first" person is null so we know that we can call "first.Equals()" without throwing an exception and will then pass the responsibility for the rest of the evaluation to the "Equals()" method.
- public static Boolean operator == (Person first, Person second)
- {
- if (ReferenceEquals(first, second))
- {
- return true;
- }
-
- if (ReferenceEquals(first, null))
- {
- return false;
- }
-
- return first.Equals(second);
- }
Trap #2The infinite recursion problem can span multiple methods in this more subtle. If we have implemented the equality operator "==" as above, but then use the equality operator to check for referential equality in the "Equals()" method, we will end up with another infinite recursion.
- public bool Equals(Person other)
- {
- if (other == null)
- {
- return false;
- }
-
-
- }
To resolve this issue, we can once again use the "ReferenceEquals" method to check for referential equality.
- public bool Equals(Person other)
- {
- if (ReferenceEquals(other, null))
- {
- return false;
- }
-
-
- var result = _Identifier.Equals(other._Identifier);
-
- return result;
- }
If we are working with a code base that uses equality for checking referential equality, then there is a very high risk of introducing infinite recursive loops if ever someone decided to implement the equality operator "==" as the code base matures. These types of defects are particularly nasty in that they are not caught by the compiler and will only manifest run time and only when you check equality. This leaves defect traps that can take our entire application down potentially that may only be executed in edge cases. Another thing making them difficult to deal with is that deciphering multiple circular method calls is not a trivial task.
If you value your weekends like I do and do not like being called up at 3am on Saturday to put out fires in production, then we are safer betting on using "ReferenceEquals()" rather than the equality operator "==" to check referential equality.
Trap #3Another thing we have to be careful of is making sure the identifier is not null. This can be accomplished through guard clauses in the constructor.
- public Person(String identifier)
- {
- if (ReferenceEquals(identifier, null))
- {
- throw new ArgumentNullException(identifier);
- }
-
- _Identifier = identifier;
- }
If the identifier is a string, we might want to consider not allowing whitespace or empty strings as well, but that depends on the business domain we are modeling. At the very least we need to check for null to protect the "Equal()" method from throwing a null reference exception.
- if(String.IsNullOrEmpty(identifier)){}
- if(String.IsNullOrWhiteSpace(identifier)){}
Trap #4Since we are overriding the "Equals()" method, we should also override the "GetHashcode()" method. If we don't have a good understanding of the implications of overriding "GetHashcode()" it is easy to introduce a bunch of subtle defects into the system. "GetHashcode()" is used to get an identifier that is used to keep track of your instance. By default, "GetHashcode()" is based off the instance. Here are some of the defects that are easy to introduce.
Let's say we have a "User" class where we have implemented equality:
- c class User: IEquatable
- {
- private Int32 _ID;
-
- public User(Int32 id)
- {
- _ID = id;
- }
-
- public override bool Equals(object obj)
- {
- return Equals(obj as User);
- }
-
- public bool Equals(User other)
- {
- return _ID == other._ID;
- }
- }
If we do not implement "GetHashcode()" then we can get unexpected behaviors. For example, if we use our "User" class as a dictionary key, even though we have implemented equality, we are using the instance to generate a hash to find the class instead of the identifier.
- User a = new User(1);
- User b = new User(2);
-
- var friends = new Dictionary<User, User>() { {a , b} };
-
- User c = new User(1);
-
- var areEqual = a.Equals(c);
-
- var containsA = friends.ContainsKey(a);
- var containsC = friends.ContainsKey(c);
This can create subtle defects in our code base. If we want consistent behavior, "GetHashcode()" should always be implemented if we implement "Equals()".
- public class User: IEquatable
- {
- private Int32 _ID;
-
- public User(Int32 id)
- {
- _ID = id;
- }
-
- public override bool Equals(object obj)
- {
- return Equals(obj as User);
- }
-
- public bool Equals(User other)
- {
- return _ID == other._ID;
- }
-
- public override int GetHashCode()
- {
- return _ID.GetHashCode();
- }
- }
Now it will behave as expected:
- User a = new User(1);
- User b = new User(2);
-
- var friends = new Dictionary<User, User>() { {a , b} };
-
- User c = new User(1);
-
- var areEqual = a.Equals(c);
-
- var containsA = friends.ContainsKey(a);
- var containsC = friends.ContainsKey(c);
Trap #5A problem that can arrive when implementing "GetHashcode()" is when the identifier changes.
- public class User: IEquatable
- {
- private Int32 _ID;
-
- public User(Int32 id)
- {
- _ID = id;
- }
-
- public override bool Equals(object obj)
- {
- return Equals(obj as User);
- }
-
- public bool Equals(User other)
- {
- return _ID == other._ID;
- }
-
- public override int GetHashCode()
- {
- return _ID.GetHashCode();
- }
-
- public Int32 ID
- {
- get
- {
- return _ID;
- }
- set
- {
- _ID = value;
- }
- }
- }
If the identifier changes, we can "loose" our instance.
- User a = new User(1);
- User b = new User(2);
-
- var friends = new Dictionary<User, User>() { {a , b} };
-
- var contains1 = friends.ContainsKey(a);
-
- a.ID = 3;
-
- var contains2 = friends.ContainsKey(a);
In order to avoid this behavior, we should always make identifying information immutable in both entity and value objects.
- public class User: IEquatable
- {
- private readonly Int32 _ID;
-
- public User(Int32 id)
- {
- _ID = id;
- }
-
- public override bool Equals(object obj)
- {
- return Equals(obj as User);
- }
-
- public bool Equals(User other)
- {
- return _ID == other._ID;
- }
-
- public override int GetHashCode()
- {
- return _ID.GetHashCode();
- }
-
- public Int32 ID
- {
- get {
- return _ID;
- }
- }
- }
Wrap-UpTo finish our implementation, we just need to implement our overridden "Equals" method by casting the type to a "Person" class and then call the "IEquality.Equals()" method. This way, if we are passed a type that is anything other than a "Person" instance, the soft cast ("as") will return null.
- public override bool Equals(object obj)
- {
- return Equals(obj as Person);
- }
- Finally, we implement the inequality‘ != ’operator which is required when we implement the equality‘ == ’operator
-
- public static Boolean operator != (Person first, Person second)
- {
- return !(first == second);
- }
This is how I arrived at my
recommended implementation of equality.
[Original article] Until next time
Happy Coding