Reputation: 11478
I've got an entity that I build, I take an instantiated entity and a modified entity. This allows me to hold the initial data, to compare against the modified data. The question, is what would be the ideal approach? Should I implement IEquatable
as an override on Object.Equals
or implement ICompare
? My original implementation was:
var properties = typeof(TEntity).GetProperties();
foreach(var property in properties)
{
var initialEntity = original.GetType().GetProperty(property.Name).GetValue(original, null);
var modifiedEntity = userChange.GetType().GetProperty(property.Name).GetValue(userChange, null);
if(initialEntity.Equals(modifiedEntity) == false && !ignore.Contains(property.Name))
{
// Do Something
}
}
My understanding was that it would return a boolean
, also in this instance it would compare on Value Equality, I'm assuming though it is comparing based on reference equality.
Because it never distinguishes, it remains equal under all circumstances.
Upvotes: 1
Views: 77
Reputation: 11463
The simplest answer:
IEquatable<T>
and override Equals()
and GetHashCode()
IComparable<T>
The default implementation of Object.Equals()
determines if the memory location used by one object is the same as another object. This is essentially what Object.ReferenceEquals(obj1, obj2)
does, but dot net needs you to tell it how to determine if two objects you create are equivalent.
Additionally, the default implementation of Object.GetHashCode()
is the 32 bit address (or portion of an address) of where the object is located in memory. Unless you override it to generate a hash code that is a function of everything you compared in your Equals()
method, you will get unexpected results when you attempt to store it in a hash set or use it as a dictionary key.
You may need to implement both, but it looks like in your case IEquatable<T>
is the most pressing need.
Upvotes: 3