0

I am trying to check a Dictionary whether or not a certain Object is contained as a key:

  Dictionary<Order, int> occurence = new Dictionary<Order, int>();
  if (occurence.ContainsKey(order)) {
      occurence[order] += 1;
  } else {
      occurence.Add(order,1);
  }

The Order class consists of a simple Dictionary in which I map the properties to their values:

private Dictionary<String, String> properties = new Dictionary<string, string>();

I implemented the HashCode function for the Order class, since the Dictionary lookup depends on it for comparison:

  public override int GetHashCode() {
       return properties.GetHashCode();
  }

Problem is that no matter what the order is not found in the Dictionary. Any idea how to fix this?

Curunir
  • 1,186
  • 2
  • 13
  • 30
  • The answer explains why it is important to implement both GetHashCode and Equals, even though you have the opposite situation. So basically you must implement `Equals(object)` as well. – Lasse V. Karlsen Jul 25 '17 at 13:06
  • The default implementation of `GetHashCode` depends on so-called 'Object identity'. If you have two `Dictionary` instances which have the same keys and values, they are not guaranteed to have the same hash code. You may be passing a dictionary with exactly the same values, but it won't have the same hash code, and the default `Equals` will also return false, so you won't get a hit. – Oly Jul 25 '17 at 13:08
  • First you must also implement `Equals` second all you're doing is a hash of the dictionary object, not the values in the dictionary, so unless you actually pass dictionary references between your `Order` classes that's not going to do what I presume you think it does. – juharr Jul 25 '17 at 13:08
  • Ok, I thought the lookup implementation uses hashcode directly and does not use equals... – Curunir Jul 25 '17 at 13:08
  • 1
    @Curunir It has to use both since hash codes are not guaranteed to be unique (only that equal objects have the same hash code). They just get you to a bucket and then `Equals` is used to find exact matches. – juharr Jul 25 '17 at 13:11
  • So what is a good implementation for HashCode on the Dictionary? I used the "standard" java solution with prime and multiplication of strings hashcode but it produces a stackoverflow with an int... – Curunir Jul 25 '17 at 13:12
  • 1
    The hashcode is used to filter down the number of objects you need to call equals on, you still need both – Scott Chamberlain Jul 25 '17 at 13:12
  • @Curunir By default .Net will allow numeric overflow (`int.MaxValue + 1` will result in `int.MinValue`), if you're getting a stack overflow then you're using something that's repetitively creating stacks like a recursive algorithm of some type. – juharr Jul 25 '17 at 13:17
  • I overrode the Equals Method and I also implemented IEquatable but neither get called. – Curunir Jul 25 '17 at 13:20

0 Answers0