Skip to content

Instantly share code, notes, and snippets.

@DavidBrower
Created September 1, 2015 16:24
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save DavidBrower/86b663021f909801a480 to your computer and use it in GitHub Desktop.
Save DavidBrower/86b663021f909801a480 to your computer and use it in GitHub Desktop.
ValueObject Base Class
public abstract class ValueObject<T> : IEquatable<T> where T : ValueObject<T>
{
private List<PropertyInfo> Properties { get; }
protected ValueObject()
{
Properties = new List<PropertyInfo>();
}
public override Boolean Equals(object obj)
{
if (ReferenceEquals(null, obj)) return false;
if (obj.GetType() != GetType()) return false;
return Equals(obj as T);
}
public bool Equals(T other)
{
if (ReferenceEquals(null, other)) return false;
if (ReferenceEquals(this, other)) return true;
foreach (var property in Properties)
{
var myValue = property.GetValue(this, null);
var otherValue = property.GetValue(other, null);
if (null == myValue || null == otherValue) return false;
if (false == myValue.Equals(otherValue)) return false;
}
return true;
}
public override int GetHashCode()
{
var hashCode = 36;
foreach (var property in Properties)
{
var propertyValue = property.GetValue(this, null);
if (null == propertyValue)
continue;
hashCode = hashCode ^ propertyValue.GetHashCode();
}
return hashCode;
}
public override string ToString()
{
var stringBuilder = new StringBuilder();
foreach (var property in Properties)
{
var propertyValue = property.GetValue(this, null);
if (null == propertyValue)
continue;
stringBuilder.Append(propertyValue.ToString());
}
return stringBuilder.ToString();
}
protected void RegisterProperty(Expression<Func<T, object>> expression)
{
if (expression == null) throw new ArgumentNullException(nameof(expression));
MemberExpression memberExpression;
if (ExpressionType.Convert == expression.Body.NodeType)
{
var body = (UnaryExpression)expression.Body;
memberExpression = body.Operand as MemberExpression;
}
else
{
memberExpression = expression.Body as MemberExpression;
}
if (null == memberExpression)
{
throw new InvalidOperationException("InvalidMemberExpression");
}
Properties.Add(memberExpression.Member as PropertyInfo);
}
public static bool operator ==(ValueObject<T> x, ValueObject<T> y)
{
return x.Equals(y);
}
public static bool operator !=(ValueObject<T> x, ValueObject<T> y)
{
return !(x == y);
}
}
@exalted
Copy link

exalted commented Apr 18, 2016

protected void RegisterProperty(Expression<Func<T, object>> expression)

@DavidBrower quick question: where/how is this method used please?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment