If you remember the post String Typed Models, I was mentioning that class ModelBase was implementing the IComparable generic interface.
The reason for doing so is to be able to easily compare two implementation of ModelBase. This is especially useful when we need to sort models or put them in some kind of sorted collections.
For example, when building ISet collections of models, we need to either have the set populated with objects that implement IComparable or provide an external comparator.
When implementing the IComparable, we need to implement the CompareTo method. I decided to compare two ModelBase objects by comparing their Id (which is their TcmUri). In other words, two models are the same, if they have the same TcmUri.
A slightly different scenario is when we need to put a ModelBase in a ISet implementation, such as HashSet. In this case, the extremely confusing equality framework of .net can be summarized by simply overriding the default GetHashCode() and Equals(object) methods. There will be no other requirements such as implementing IEquatable or IEqualityComparer, etc. The code below illustrates the overridden implementations:
public class ModelBase : IComparable<ModelBase>
For example, when building ISet collections of models, we need to either have the set populated with objects that implement IComparable or provide an external comparator.
When implementing the IComparable, we need to implement the CompareTo method. I decided to compare two ModelBase objects by comparing their Id (which is their TcmUri). In other words, two models are the same, if they have the same TcmUri.
public int CompareTo(ModelBase other)
{
if
(other == null)
{
return 1;
}
string otherId = other.Id;
if
(Id == null && otherId == null)
{
return 0;
}
else
if (otherId == null)
{
return 1;
}
else
if (Id == null)
{
return -1;
}
return Id.CompareTo(otherId);
}
A slightly different scenario is when we need to put a ModelBase in a ISet implementation, such as HashSet. In this case, the extremely confusing equality framework of .net can be summarized by simply overriding the default GetHashCode() and Equals(object) methods. There will be no other requirements such as implementing IEquatable or IEqualityComparer, etc. The code below illustrates the overridden implementations:
public override int GetHashCode()
{
return Id.GetHashCode();
}
public override bool Equals(object other)
{
if
(other == null || !(other is ModelBase))
{
return false;
}
string otherId = ((ModelBase)other).Id;
if
(Id == null && otherId == null)
{
return true;
}
else
if (otherId == null || Id == null)
{
return false;
}
return Id.Equals(otherId);
}
Comments