1

Is there an easy way to make a hash key for a class based on it's data??? Or some interface for that?

I have a Dictionary<MyClass, int>.

MyClass is very simple, it contains a name and a string array:

class MyClass
{
    public string Name {get; private set;}
    public string[] Attributes {get; private set; }

    //and a constructor and some methods
}

Now, if I have two MyClass instances containing same names and attributes, I need that dictionary to consider as if they have same key.

I tried to make it a struct, and tried to make a Dictionary<string[], int> as well, but all three cases are equal, dicionary sees different keys for every instance, even if with same data.

I could create a string key with an algorithm taking name and all parameters, and create a Dictionary<string, int>, but I'd like something more automatic. Is there any other way? Maybe an interface (that would't avoid an algorythm, but is better than nothing).

Daniel Möller
  • 84,878
  • 18
  • 192
  • 214
  • possible duplicate of [When do we do GetHashCode() for a Dictionary?](http://stackoverflow.com/questions/1407380/when-do-we-do-gethashcode-for-a-dictionary) (Also relevant: [Why is it important to override GetHashCode when Equals method is overridden?](http://stackoverflow.com/questions/371328/why-is-it-important-to-override-gethashcode-when-equals-method-is-overridden)) – Kirk Woll May 17 '13 at 18:02
  • Does the order of the strings in `Attributes` matter? Case? Is a `null` `Attributes` member equal to a non-null but empty one? Having two of these classes be "equal" is not obvious or simple. – dlev May 17 '13 at 18:03
  • Everything matters, but null attributes are impossible. (Empty allowed) – Daniel Möller May 17 '13 at 18:16

1 Answers1

4

You need to override Equals() and GetHashCode() to compare instances by value.

SLaks
  • 868,454
  • 176
  • 1,908
  • 1,964
  • Nice....but....create an `int` hash would be terrible. And with so many strings it would very probably be insufficient. Is `Equals()` sufficient to make dictionary recognize them as same? – Daniel Möller May 17 '13 at 18:09
  • 1
    @Daniel: No. The whole point of a dictionary is to use the hash code to create an index for each object. (read about hash tables on Wikipedia) – SLaks May 17 '13 at 18:11
  • Right, but, a string with 32 character has surely more combinations than a 32 bit int. How can dicionaries handle that using an int32 hash code? – Daniel Möller May 17 '13 at 18:14
  • 1
    @Daniel Hash values aren't unique. They are meant to avoid duplicate values as much as possible (in balance with other factors, e.g. generation speed), but they still happen. Look up "hash collision". – itsme86 May 17 '13 at 18:23