C# ContainsKey does not find Key in dictionary alltough it is present

88 views Asked by At

EDIT: This is no longer about GetHashCode!

I'm implementing a game with Unity/C# and have a dictionary of effects where the key is the System.Type of the effect and the value is a list of effects registered for that type.

When I want to query effects from the dictionary the ContainsKey method does not find any keys after my dictionary got deserialized by some Json.Net logic. (works in other cases). However, the dictionary does contain types with correct hashcodes.

public bool GetEffects<T>(out List<T> queriedEffects) where T : Effect
{
  queriedEffects = null;
  int test = typeof(T).GetHashCode();
  foreach(Type t in activePersistantEffects.keys)
  {

     if (t.GetHashCode() == test)
     { Debug.Log("Hashcode is working"); } //Prints to log correctly

     if (t == typeof(T))
     { Debug.Log("== is working"); } //Does not print to log

     if (t.Equals(typeof(T)))
     { Debug.Log(".Equals() is working"); } //Does not print to log
  }
  if (activePersistantEffects.ContainsKey(typeof(T))) //Returns false
  {
      queriedEffects = activePersistantEffects.GetEffects<T>();
      return true;
  }
  return false;
}

Since the hash code is equal for the concrete instances in the KeyCollection I thought this must work?

Any thoughts suggestions? Would really like to solve this without having to rework a bunch of the codebase^^ Thanks in advance guys!

Edit: After trying to debug via the FullName attribute I am even more puzzled. The types seem to be equivalent: Method returns false even tough FullNames of types are equivalent.

0

There are 0 answers