Skip to content

Instantly share code, notes, and snippets.

@Van-Dame
Created September 21, 2018 06:53
Show Gist options
  • Save Van-Dame/90253cd21be7e780002a70166b2b9920 to your computer and use it in GitHub Desktop.
Save Van-Dame/90253cd21be7e780002a70166b2b9920 to your computer and use it in GitHub Desktop.
Base Domain Modelling classes
public abstract class Entity
{
public virtual long Id { get; protected set; }
protected virtual object Actual => this;
public override bool Equals(object obj)
{
var other = obj as Entity;
if (other is null)
return false;
if (ReferenceEquals(this, other))
return true;
if (Actual.GetType() != other.Actual.GetType())
return false;
if (Id == 0 || other.Id == 0)
return false;
return Id == other.Id;
}
public static bool operator ==(Entity a, Entity b)
{
if (a is null && b is null)
return true;
if (a is null || b is null)
return false;
return a.Equals(b);
}
public static bool operator !=(Entity a, Entity b)
{
return !(a == b);
}
public override int GetHashCode()
{
return (Actual.GetType().ToString() + Id).GetHashCode();
}
}
public abstract class ValueObject<T> where T : ValueObject<T>
{
public override bool Equals(object obj)
{
var valueObject = obj as T;
if (ReferenceEquals(valueObject, null))
return false;
return EqualsCore(valueObject);
}
protected abstract bool EqualsCore(T other);
public override int GetHashCode()
{
return GetHashCodeCore();
}
protected abstract int GetHashCodeCore();
public static bool operator ==(ValueObject<T> a, ValueObject<T> b)
{
if (ReferenceEquals(a, null) && ReferenceEquals(b, null))
return true;
if (ReferenceEquals(a, null) || ReferenceEquals(b, null))
return false;
return a.Equals(b);
}
public static bool operator !=(ValueObject<T> a, ValueObject<T> b)
{
return !(a == b);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment