Created
November 7, 2023 17:18
-
-
Save light-traveller/af75e68324e74fcc4146f3dcd3e5703f to your computer and use it in GitHub Desktop.
DDD ValueObject
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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