Last active
July 16, 2024 08:06
-
-
Save zsmahi/dcced370c876dab5acd969208063391a to your computer and use it in GitHub Desktop.
StronglyTypedId generic class + Generic ValueObject class
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 StronglyTypedId<TValue> where TValue : notnull | |
{ | |
protected StronglyTypedId(TValue value) | |
{ | |
if (!IsValid(value)) | |
{ | |
throw new ArgumentException($"{value} is not a valid value for this id"); | |
} | |
Value = value; | |
} | |
public TValue Value { get; } | |
public static bool operator !=(StronglyTypedId<TValue> left, StronglyTypedId<TValue> right) | |
=> !(left == right); | |
public static bool operator ==(StronglyTypedId<TValue> left, StronglyTypedId<TValue> right) | |
=> left.Equals(right); | |
public override bool Equals(object? obj) | |
=> obj is StronglyTypedId<TValue> other && Value.Equals(other.Value); | |
public override int GetHashCode() | |
=> Value.GetHashCode(); | |
public abstract bool IsValid(TValue value); | |
public override string ToString() | |
=> Value.ToString() ?? string.Empty; | |
} |
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> | |
{ | |
private const int PrimeNumber = 23; | |
public static bool operator !=(ValueObject a, ValueObject b) | |
=> !(a == b); | |
public static bool operator ==(ValueObject a, ValueObject b) | |
{ | |
if(a is null || b is null) | |
{ | |
return a is null && b is null; | |
} | |
return a.Equals(b); | |
} | |
public override bool Equals(object obj) | |
=> obj is ValueObject valueObject && Equals(valueObject); | |
public bool Equals(ValueObject other) | |
{ | |
if (other is null) | |
{ | |
return false; | |
} | |
if (ReferenceEquals(this, other)) | |
{ | |
return true; | |
} | |
return GetEqualityComponents().SequenceEqual(other.GetEqualityComponents()); | |
} | |
public override int GetHashCode() | |
{ | |
unchecked | |
{ | |
int hash = base.GetHashCode(); | |
foreach (object component in GetEqualityComponents()) | |
{ | |
hash = (hash * PrimeNumber) + (component?.GetHashCode() ?? 0); | |
} | |
return hash; | |
} | |
} | |
protected abstract IEnumerable<object> GetEqualityComponents(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment