I have a structure in C#:
public struct UserInfo
{
public string str1
{
get;
set;
}
public string str2
{
get;
set;
}
MSDN:
A hash function must have the following properties:
- If two objects compare as equal, the
GetHashCodemethod for each object must return the same value. However, if two objects do not compare as equal, theGetHashCodemethods for the two object do not have to return different values.- The
GetHashCodemethod for an object must consistently return the same hash code as long as there is no modification to the object state that determines the return value of the object'sEqualsmethod. Note that this is true only for the current execution of an application, and that a different hash code can be returned if the application is run again.- For the best performance, a hash function must generate a random distribution for all input.
Taking it into account correct way is:
return str1.GetHashCode() ^ str2.GetHashCode()
^ can be substituted with other commutative operation
public override int GetHashCode()
{
unchecked
{
return(str1 != null ? str1.GetHashCode() : 0) ^ (str2 != null ? str2.GetHashCode() : 0);
}
}