I've overridden Equals and GetHashCode in an abstract base class to implement value equality based on an object's key property. My main purpose is to be able to use the Contains method on collections instead of Find or FirstOrDefault to check if an instance has already been added to a collection.
public abstract class Entity
{
public abstract Guid Id { get; }
public override bool Equals(object obj)
{
if (obj == null)
{
return false;
}
if (obj.GetType() != GetType())
{
return false;
}
var entity = (Entity)obj;
return (entity.Id == Id);
}
public override int GetHashCode()
{
return Id.GetHashCode();
}
}
The problem with this approach is that all my objects are equal before they've been persisted and acquired an Id (generated by NHibernate). Am I doing it wrong? I could generate the Id in the constructor, but I would like to implement the same pattern for other projects that use int ids, so that obviously won't work.
It seems to me that any object that overrides Equals will be equal to any other instance of the same object immediately after the objects have been instantiated.
Edited to add: Here's the scenario that concerns me: In the Add method for my collections, I am checking to make sure that the collection does not already contain the object to be added. If all new'ed up objects are equal, then I can never add two new objects to the collection.