Created
March 15, 2024 18:48
-
-
Save mt89vein/1aa33e06bef91be907df3a06d2dd6b83 to your computer and use it in GitHub Desktop.
Value object base class example
This file contains 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 : 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