Let's say I have a POCO that represents a database row. I have access to the ID of that row.
Is it safe to implement GetHashCode and Equals by leveraging that unique ID ?
public class Project
{
public string ID { get; }
public string Name { get; set; }
public override bool Equals(object obj)
{
var pr = obj as Project;
if (pr == null) return false;
if (pr.ID == null) throw new InvalidOperationException("Attempt to .Equals an entity with null ID");
return pr.ID == ID;
}
public override int GetHashCode()
{
if (ID == null) throw new InvalidOperationException("Attempt to .GetHashCode on an entity with null ID");
return ID.GetHashCode();
}
}
I believe this could work because
- ID is not mutable
- I handle the case where ID is null
Any thoughts on that ?