I have an object that has a multi-part key and I am struggling to find a suitable way override GetHashCode. An example of what the class looks like is.
public class wibble{
public int keypart1 {get; set;}
public int keypart2 {get; set;}
public int keypart3 {get; set;}
public int keypart4 {get; set;}
public int keypart5 {get; set;}
public int keypart6 {get; set;}
public int keypart7 {get; set;}
public single value {get; set;}
}
Note in just about every instance of the class no more than 2 or 3 of the keyparts would have a value greater than 0.
Any ideas on how best to generate a unique hashcode in this situation?
I have also been playing around with creating a key that is not unique, but spreads the objects evenly between the dictionaries buckets and then storing objects with matched hashes in a List<> or LinkedList<> or SortedList<>.
Any thoughts on this?
The simplest method is to use XOR. A slightly better method is the one recommended by Josh Bloch in Effective Java. See here.
Regarding your use of the hash code: it is expected that there will sometimes be collisions and this should not cause problems (having too many collisions will make your code slow, but it should still work). If you can have multiple values for the same key you should consider using something like a
Dictionary<Foo, List<Bar>>or aLookup. If the hashes of the keys happen to collide but the keys are different then you don’t need to do anything special.Dictionaryhandles this situation for you automatically, as long as your implementation of Equals is correct.