Skip to content

Instantly share code, notes, and snippets.

@light-traveller
Created November 7, 2023 17:18
Show Gist options
  • Save light-traveller/af75e68324e74fcc4146f3dcd3e5703f to your computer and use it in GitHub Desktop.
Save light-traveller/af75e68324e74fcc4146f3dcd3e5703f to your computer and use it in GitHub Desktop.
DDD ValueObject
public abstract class ValueObject
{
protected abstract IEnumerable<object> GetEqualityComponents();
public override bool Equals(object? other)
{
if (other is null || other.GetType() != GetType())
{
return false;
}
var otherValue = (ValueObject)other;
return GetEqualityComponents().SequenceEqual(otherValue.GetEqualityComponents());
}
public override int GetHashCode()
{
var hash = new HashCode();
foreach (var c in GetEqualityComponents())
{
hash.Add(c ?? 0);
}
return hash.ToHashCode();
}
public static bool operator ==(ValueObject left, ValueObject right)
{
if (left is null ^ right is null)
{
return false;
}
return left is null || left.Equals(right);
}
public static bool operator !=(ValueObject left, ValueObject right)
{
return !(left == right);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment