I'm trying to create a hashcode method. I have code like below :
private static object GetValue<T>(object item, string propertyName)
{
ParameterExpression arg = Expression.Parameter(item.GetType(), "x");
Expression expr = Expression.Property(arg, propertyName);
UnaryExpression unaryExpression = Expression.Convert(expr, typeof(object));
var propertyResolver = Expression.Lambda<Func<T, object>>(unaryExpression, arg).Compile();
return propertyResolver((T)item);
}
private static int GetHashCode<T>(T obj, List<string> columns)
{
unchecked
{
int hashCode = 17;
for (var i = 0; i < columns.Count; i++)
{
object value = GetValue<T>(obj, columns[i]);
var tempHashCode = value == null ? 0 : value.GetHashCode();
hashCode = (hashCode * 23) + tempHashCode;
}
return hashCode;
}
}
private static void TestHashCode()
{
var t1 = new { ID = (long)2044716, Type = "AE", Method = (short)1022, Index = 3 };
var t2 = new { ID = (long)12114825, Type = "MEDAPE", Method = (short)1700, Index = 2 };
var e1 = t1.GetHashCode();
var e2 = t2.GetHashCode();
var columns = new[] { "ID", "Type", "Method", "Index" }.ToList();
var k1 = GetHashCode(t1, columns);
var k2 = GetHashCode(t2, columns);
}
The e1 value is -410666035, The e2 value is 101205027. The k1 value is 491329214. The k2 value is 491329214.
HashCode Steps:
hashCode = 17
tempHashCode = 2044716
hashcode = 2045107
tempHashCode = 1591023428
hashcode = 1638060889
tempHashCode = 66978814
hashcode = -912326403
tempHashCode = 3
hashcode = 491329214
How can k1 and k2 be the same value ? Because default .net gethashcode method gives two different values. I want to create a hashcode method that can get column list. I want to create a hash code by particular properties. I'm trying to get a unique value for object by particular properties.
How can I identify object by particular properties if GetHashCode doesn't guarantee unique value ?