Now, I am going to describe this process on a particular example to check whether it will allow us to determine the use of the object comparison by value in general and thus, to simplify a sample of comparing objects by value – class instances that represent reference types.
In the previous article, we analyzed how to compare objects by value on a particular example with the Person class that includes:
- Overriding the GetHashCode() andObject.Equals(Object) methods;
- Implementation of the IEquatable (Of T) interface;
- Implementation of the type-specific static method Equals(Person, Person) and operators ==(Person, Person), !=(Person, Person).
Now, we will explore a type-specific implementation of how to compare objects by value including the IEquatable(Of T) generic interface and overload of “==” and “!=” operators.
Type-specific comparison of objects by value allows achieving:
- a more stable, scalable and mnemonic (readable) code through overloaded operators;
- higher performance.
In the previous article, we have reviewed a general concept of implementing a minimum set of required modifications that include overriding the Object.Equals(Object) and Object.GetHashCode() methods in order to compare class objects by value on a standard .NET framework.
Let’s consider the implementation features of the Object.Equals(Object) method so that it meets the following documentation requirement:
x.Equals(y) returns the same value as y.Equals(x).
It is a common fact that the .NET object model, as well as other software program platforms, allow comparing objects by reference and by value.
By default, two objects are equal if the corresponding object variables have the same reference. Otherwise, they are different.
However, in some cases, you may need to state that two objects belonging to the same class are equal if their content match in a certain way.
Assume we have the Person class, which contains some personal data – First Name, Last Name, and Birth date.
Consider the following points:
- What is the minimum required number of class modifications to assure comparing class objects by values with the help of the standard .NET architecture?
- What is the minimum required number of class modifications to assure comparing class objects by values (every time, if not explicitly stated that objects may be compared by a reference) with the help of the standard .NET architecture?
For each case, we will see the best way to compare objects by value to get a consistent, compact, copy-paste free, and productive code. It is not as trivial as it may seem for the first time.