Skip to content

Instantly share code, notes, and snippets.

@seburgi
Created April 11, 2013 19:31
Show Gist options
  • Save seburgi/5366479 to your computer and use it in GitHub Desktop.
Save seburgi/5366479 to your computer and use it in GitHub Desktop.
Generates a hashcode for simple objects that depends on its contents.
public class HashCodeGenerator<T>
{
private readonly List<Func<T, object>> _getters = new List<Func<T, object>>();
public HashCodeGenerator()
{
PropertyInfo[] properties = typeof(T).GetProperties();
foreach (var p in properties)
{
Func<T, object> getter = GetValueGetter<T>(p);
_getters.Add(getter);
}
}
public int Generate(T o)
{
int hashCode = 0;
foreach (var getter in _getters)
{
object value = getter(o);
hashCode = (hashCode * 397) ^ (value != null ? value.GetHashCode() : 0);
}
return hashCode;
}
private static Func<T, object> GetValueGetter<T>(PropertyInfo propertyInfo)
{
ParameterExpression instance = Expression.Parameter(propertyInfo.DeclaringType, "i");
MemberExpression property = Expression.Property(instance, propertyInfo);
UnaryExpression convert = Expression.TypeAs(property, typeof(object));
return Expression.Lambda<Func<T, object>>(convert, instance).Compile();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment