Search code examples
c#dictionaryequalsgethashcode

What can cause dictionary.ContainsKey(dictionary.Keys.First()) to return false?


dictionary.Keys.First().GetHashCode() == dictionary.Keys.First().GetHashCode() returns true dictionary.Keys.First() == dictionary.Keys.First() returns true

What's missing? Why can't the dictionary find this object?

Type of dictionary: Dictionary<ExceptionWrapper<Exception>, List<int>>.

Here is the implementation of ExceptionWrapper.Equals and ExceptionWrapper.GetHashCode:

public override int GetHashCode() {
  return (typeof(TException).FullName + exception.Message + exception.StackTrace).GetHashCode();
}

public override bool Equals(object obj) {
  return 
    obj is ExceptionWrapper<TException>
&& (obj as ExceptionWrapper<TException>).GetHashCode() == GetHashCode();
}

Solution

  • The key was first added to the Dictionary<,> when it had one hash code. After that the object was "mutated" to give a state where the hash code is some new number.

    The Dictionary<,> is therefore in an invalid state.

    Do not mutate an object that might be a key in some hashtable somewhere, in a way the changes the hash code of that object.