G
Guest
I'm trying to write a generic method to generate Hashcodes but am having some
problems with (generic) collections. Here is the code of my method:
public static int GetHashCode(object input)
{
try
{
Type objectType = input.GetType();
PropertyInfo[] properties = objectType.GetProperties();
int totalHashCode = 7;
foreach (PropertyInfo property in properties)
{
// Reset hashcode
int hashcode = 0;
// Get property value
object value = property.GetValue(input, null);
// Invoke GetHashCode method on property
if (property.PropertyType.IsValueType || value !=
null)
{
int.TryParse(property.PropertyType.InvokeMember("GetHashCode",
BindingFlags.Default | BindingFlags.InvokeMethod, null, value, null,
CultureInfo.InvariantCulture).ToString(), out hashcode);
}
totalHashCode ^= hashcode;
}
return totalHashCode;
}
catch(Exception)
{
// Handle exception
return 0;
}
}
public class Customer{
public Customer(){}
public string Name{get{return "Mr Blobby";}}
public string Telephone{get{return "999";}}
}
public class CustomerCollection : List<Customer>
{
public CustomerCollection(){}
}
The problem I am having is that this method doesn't really take into account
objects which are(generic) collections. eg.. (excusing my simplicity) the
Customer class would work but the Customer Collection wouldn't. Can anyone
give me some pointers to improve this? Cheers in advance for any tips!
problems with (generic) collections. Here is the code of my method:
public static int GetHashCode(object input)
{
try
{
Type objectType = input.GetType();
PropertyInfo[] properties = objectType.GetProperties();
int totalHashCode = 7;
foreach (PropertyInfo property in properties)
{
// Reset hashcode
int hashcode = 0;
// Get property value
object value = property.GetValue(input, null);
// Invoke GetHashCode method on property
if (property.PropertyType.IsValueType || value !=
null)
{
int.TryParse(property.PropertyType.InvokeMember("GetHashCode",
BindingFlags.Default | BindingFlags.InvokeMethod, null, value, null,
CultureInfo.InvariantCulture).ToString(), out hashcode);
}
totalHashCode ^= hashcode;
}
return totalHashCode;
}
catch(Exception)
{
// Handle exception
return 0;
}
}
public class Customer{
public Customer(){}
public string Name{get{return "Mr Blobby";}}
public string Telephone{get{return "999";}}
}
public class CustomerCollection : List<Customer>
{
public CustomerCollection(){}
}
The problem I am having is that this method doesn't really take into account
objects which are(generic) collections. eg.. (excusing my simplicity) the
Customer class would work but the Customer Collection wouldn't. Can anyone
give me some pointers to improve this? Cheers in advance for any tips!