Skip to content

Instantly share code, notes, and snippets.

@mt89vein
Created March 15, 2024 18:48
Show Gist options
  • Save mt89vein/1aa33e06bef91be907df3a06d2dd6b83 to your computer and use it in GitHub Desktop.
Save mt89vein/1aa33e06bef91be907df3a06d2dd6b83 to your computer and use it in GitHub Desktop.
Value object base class example
public abstract class ValueObject : IEquatable<ValueObject>
{
public bool Equals(ValueObject? other)
{
if (ReferenceEquals(this, other))
{
return true;
}
return other is not null &&
GetEqualityComponents().SequenceEqual(other.GetEqualityComponents());
}
public override bool Equals(object? obj)
{
if (obj is null || obj.GetType() != GetType())
{
return false;
}
return Equals((ValueObject)obj);
}
public override int GetHashCode()
{
var hash = new HashCode();
foreach (var i in GetEqualityComponents())
{
hash.Add(i);
}
return hash.ToHashCode();
}
public static bool operator ==(ValueObject? one, ValueObject? two)
{
return EqualOperator(one, two);
}
public static bool operator !=(ValueObject? one, ValueObject? two)
{
return !EqualOperator(one, two);
}
protected static bool EqualOperator(ValueObject? left, ValueObject? right)
{
if (left is null ^ right is null)
{
return false;
}
return left!.Equals(right);
}
protected abstract IEnumerable<object?> GetEqualityComponents();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment