Skip to content

Instantly share code, notes, and snippets.

@Calabonga
Created March 21, 2025 03:16
Show Gist options
  • Save Calabonga/91a57fd3d3d1fde5f535e7e5bb5fca99 to your computer and use it in GitHub Desktop.
Save Calabonga/91a57fd3d3d1fde5f535e7e5bb5fca99 to your computer and use it in GitHub Desktop.
Entity and Value Object Implementations
public abstract class Entity : IEquatable<Entity>
{
protected Entity(Guid id)
{
Id = id;
}
public Guid Id { get; private init; }
public override bool Equals(object? obj)
{
if (obj is null)
{
return false;
}
if (ReferenceEquals(this, obj))
{
return true;
}
if (obj.GetType() != GetType())
{
return false;
}
return Equals((Entity)obj);
}
public bool Equals(Entity? other)
{
if (other is null)
{
return false;
}
return ReferenceEquals(this, other) || Id.Equals(other.Id);
}
public override int GetHashCode()
{
return Id.GetHashCode();
}
public static bool operator ==(Entity? left, Entity? right) => Equals(left, right);
public static bool operator !=(Entity? left, Entity? right) => !Equals(left, right);
}
public abstract class ValueObject : IEquatable<ValueObject>
{
protected abstract IEnumerable<object> GetEqualityComponents();
public static bool operator ==(ValueObject? a, ValueObject? b)
{
if (a is null && b is null)
{
return true;
}
if (a is null || b is null)
{
return false;
}
return a.Equals(b);
}
public static bool operator !=(ValueObject? a, ValueObject? b)
{
return !(a == b);
}
public virtual bool Equals(ValueObject? other)
{
return other is not null && ValuesAreEqual(other);
}
public override bool Equals(object? obj)
{
return obj is ValueObject valueObject && ValuesAreEqual(valueObject);
}
public override int GetHashCode()
{
return GetEqualityComponents().Aggregate(0, (hashcode, value) => HashCode.Combine(hashcode, value.GetHashCode()));
}
private bool ValuesAreEqual(ValueObject valueObject)
{
return GetEqualityComponents().SequenceEqual(valueObject.GetEqualityComponents());
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment