<p>I have a structure in C#:</p>

<pre><code>public struct UserInfo
{
   public string str1
   {
     get;
     set;
   }

   public string str2
   {
     get;
     set;
   }   
}
</code></pre>

<p>The only rule is that  <code>UserInfo(str1="AA", str2="BB").Equals(UserInfo(str1="BB", str2="AA"))</code></p>

<p>How to override the GetHashCode function for this structure? </p>

[{'answer_id': 70323, 'author': 'VolkerK', 'author_id': 4833, 'author_profile': 'https://Stackoverflow.com/users/4833', 'pm_score': 0, 'selected': False, 'text': '<p>Many possibilities. E.g.<br /></p>\n\n<p><code>\nreturn str1.GetHashCode() ^ str1.GetHashCode()\n</code></p>\n'}, {'answer_id': 70326, 'author': 'Mike Stone', 'author_id': 122, 'author_profile': 'https://Stackoverflow.com/users/122', 'pm_score': 0, 'selected': False, 'text': '<p>Perhaps something like str1.GetHashCode() + str2.GetHashCode()?  or (str1.GetHashCode() + str2.GetHashCode()) / 2?  This way it would be the same regardless of whether str1 and str2 are swapped....</p>\n'}, {'answer_id': 70336, 'author': 'Artem Tikhomirov', 'author_id': 2313, 'author_profile': 'https://Stackoverflow.com/users/2313', 'pm_score': 1, 'selected': False, 'text': '<p>Try out this one:</p>\n\n<pre><code>(((long)str1.GetHashCode()) + ((long)str2.GetHashCode())).GetHashCode()\n</code></pre>\n'}, {'answer_id': 70353, 'author': 'Steve Morgan', 'author_id': 5806, 'author_profile': 'https://Stackoverflow.com/users/5806', 'pm_score': 0, 'selected': False, 'text': '<p>Sort them, then concatenate them:</p>\n\n<pre>\nreturn ((str1.CompareTo(str2) &lt; 1) ? str1 + str2 : str2 + str1)\n    .GetHashCode();\n</pre>\n'}, {'answer_id': 70373, 'author': 'Omer van Kloeten', 'author_id': 4979, 'author_profile': 'https://Stackoverflow.com/users/4979', 'pm_score': 0, 'selected': False, 'text': "<p>GetHashCode's result is supposed to be:</p>\n\n<ol>\n<li>As fast as possible.</li>\n<li>As unique as possible.</li>\n</ol>\n\n<p>Bearing those in mind, I would go with something like this:</p>\n\n<pre><code>if (str1 == null)\n    if (str2 == null)\n        return 0;\n    else\n       return str2.GetHashCode();\nelse\n    if (str2 == null)\n        return str1.GetHashCode();\n    else\n       return ((ulong)str1.GetHashCode() | ((ulong)str2.GetHashCode() &lt;&lt; 32)).GetHashCode();\n</code></pre>\n\n<p><strong>Edit:</strong> Forgot the nulls. Code fixed.</p>\n"}, {'answer_id': 70375, 'author': 'aku', 'author_id': 1196, 'author_profile': 'https://Stackoverflow.com/users/1196', 'pm_score': 7, 'selected': True, 'text': '<p><a href="http://msdn.microsoft.com/en-us/library/system.object.gethashcode.aspx" rel="noreferrer">MSDN</a>:</p>\n\n<p>A hash function must have the following properties:</p>\n\n<blockquote>\n  <ul>\n  <li>If two objects compare as equal, the <code>GetHashCode</code> method for each object must return the same value. However, if two objects do not compare as equal, the <code>GetHashCode</code> methods for the two object do not have to return  different values.</li>\n  <li>The <code>GetHashCode</code> method 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\'s <code>Equals</code> method. 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.</li>\n  <li>For the best performance, a hash function must generate a random distribution for all  input. </li>\n  </ul>\n</blockquote>\n\n<p>Taking it into account correct way is:</p>\n\n<pre><code>return str1.GetHashCode() ^ str2.GetHashCode() \n</code></pre>\n\n<p><code>^</code> can be substituted with other commutative operation</p>\n'}, {'answer_id': 70383, 'author': 'Grokys', 'author_id': 6448, 'author_profile': 'https://Stackoverflow.com/users/6448', 'pm_score': 2, 'selected': False, 'text': '<p>Ah yes, as Gary Shutler pointed out:</p>\n\n<pre><code>return str1.GetHashCode() + str2.GetHashCode();\n</code></pre>\n\n<p>Can overflow. You could try casting to long as Artem suggested, or you could surround the statement in the unchecked keyword:</p>\n\n<pre><code>return unchecked(str1.GetHashCode() + str2.GetHashCode());\n</code></pre>\n'}, {'answer_id': 70512, 'author': 'Roger Willcocks', 'author_id': 11511, 'author_profile': 'https://Stackoverflow.com/users/11511', 'pm_score': -1, 'selected': False, 'text': '<p>Too complicated, and forgets nulls, etc.  This is used for things like bucketing, so you can get away with something like</p>\n\n<pre><code>if (null != str1) {\n    return str1.GetHashCode();\n}\nif (null != str2) {\n    return str2.GetHashCode();\n}\n//Not sure what you would put here, some constant value will do\nreturn 0;\n</code></pre>\n\n<p>This is biased by assuming that str1 is not likely to be common in an unusually large proportion of instances.</p>\n'}, {'answer_id': 70615, 'author': 'user11556', 'author_id': 11556, 'author_profile': 'https://Stackoverflow.com/users/11556', 'pm_score': 2, 'selected': False, 'text': '<pre><code>public override int GetHashCode()   \n{       \n    unchecked      \n    {           \n        return(str1 != null ? str1.GetHashCode() : 0) ^ (str2 != null ? str2.GetHashCode() : 0);       \n    }   \n}\n</code></pre>\n'}, {'answer_id': 70739, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 4, 'selected': False, 'text': "<pre><code>public override int GetHashCode()\n{\n    unchecked\n    {\n        return (str1 ?? String.Empty).GetHashCode() +\n            (str2 ?? String.Empty).GetHashCode();\n    }\n}\n</code></pre>\n\n<p>Using the '+' operator might be better than using '^', because although you explicitly want ('AA', 'BB') and ('BB', 'AA') to explicitly be the same, you may not want ('AA', 'AA') and ('BB', 'BB') to be the same (or all equal pairs for that matter).</p>\n\n<p>The 'as fast as possible' rule is not entirely adhered to in this solution because in the case of nulls this performs a 'GetHashCode()' on the empty string rather than immediately return a known constant, but even without explicitly measuring I am willing to hazard a guess that the difference wouldn't be big enough to worry about unless you expect a lot of nulls.</p>\n"}, {'answer_id': 74820, 'author': 'Joe', 'author_id': 13087, 'author_profile': 'https://Stackoverflow.com/users/13087', 'pm_score': 3, 'selected': False, 'text': '<ol>\n<li><p>As a general rule, a simple way to generate a hashcode for a class is to XOR all the data fields that can participate in generating the hash code (being careful to check for null as pointed out by others).  This also meets the (artificial?) requirement that the hashcodes for UserInfo("AA", "BB") and UserInfo("BB", "AA") are the same.</p></li>\n<li><p>If you can make assumptions about the use of your class, you can perhaps improve your hash function.  For example, if it is common for str1 and str2 to be the same, XOR may not be a good choice.  But if str1 and str2 represent, say, first and last name, XOR is probably a good choice.</p></li>\n</ol>\n\n<p>Although this is clearly not meant to be a real-world example, it may be worth pointing out that: \n- This is probably a poor example of use of a struct:  A struct should normally have value semantics, which doesn\'t seem to be the case here.\n- Using properties with setters to generate a hash code is also asking for trouble.  </p>\n'}, {'answer_id': 1027782, 'author': 'Tomáš Kafka', 'author_id': 38729, 'author_profile': 'https://Stackoverflow.com/users/38729', 'pm_score': 5, 'selected': False, 'text': '<p>See <a href="https://stackoverflow.com/questions/263400/what-is-the-best-algorithm-for-an-overridden-system-object-gethashcode">Jon Skeet\'s answer</a> - binary operations like <code>^</code> are not good, they will often generate colliding hash!</p>\n'}, {'answer_id': 21604191, 'author': 'Jani Hyytiäinen', 'author_id': 611056, 'author_profile': 'https://Stackoverflow.com/users/611056', 'pm_score': 2, 'selected': False, 'text': "<p>Going along the lines ReSharper is suggesting:</p>\n\n<pre><code>public int GetHashCode()\n{\n    unchecked\n    {\n        int hashCode;\n\n        // String properties\n        hashCode = (hashCode * 397) ^ (str1!= null ? str1.GetHashCode() : 0);\n        hashCode = (hashCode * 397) ^ (str2!= null ? str1.GetHashCode() : 0);\n\n        // int properties\n        hashCode = (hashCode * 397) ^ intProperty;\n        return hashCode;\n    }\n}\n</code></pre>\n\n<p>397 is a prime of sufficient size to cause the result variable to overflow and mix the bits of the hash somewhat, providing a better distribution of hash codes. Otherwise there's nothing special in 397 that distinguishes it from other primes of the same magnitude.</p>\n"}, {'answer_id': 23545115, 'author': 'Daniel Lidström', 'author_id': 286406, 'author_profile': 'https://Stackoverflow.com/users/286406', 'pm_score': 2, 'selected': False, 'text': '<p>A simple <em>general</em> way is to do this:</p>\n\n<pre><code>return string.Format("{0}/{1}", str1, str2).GetHashCode();\n</code></pre>\n\n<p>Unless you have strict performance requirements, this is the easiest I can think of and I frequently use this method when I need a composite key. It handles the <code>null</code> cases just fine and won\'t cause (m)any hash collisions (in general). If you expect \'/\' in your strings, just choose another separator that you don\'t expect.</p>\n'}, {'answer_id': 67469888, 'author': 'Pablo Retyk', 'author_id': 30729, 'author_profile': 'https://Stackoverflow.com/users/30729', 'pm_score': 1, 'selected': False, 'text': '<p>Since C# 7, we can take advantage of ValueTuple for that:</p>\n<pre><code>return (str1, str2).GetHashCode();\n</code></pre>\n'}]
['https://Stackoverflow.com/questions/70303', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3834/']