c# - KeyNotFoundException when iterating through Dictionary -
i have seemingly simple piece of code consistently throwing error wouldn't expect possible:
// private member private dictionary<inputfield, bool> m_completed; // later on, during method foreach (inputfield filter in this.m_completed.keys) if (this.m_completed[filter]) completedcount += 1;
and error i'm getting:
keynotfoundexception: given key not present in dictionary
this coming "if" statement in loop.
to me, implies iterator has become desynchronised actual keys of dict. possible? there no threading going on.
is workflow wrong? can think of few other ways count, i'd still know why code throwing error.
either inputfield
or 1 of base classes implements gethashcode
in way such won't return same value lifetime of instance.
this breaks functionality of dictionary
or hashset
, rely on consistent hash code.
as such, possible solution make inputfield
override gethashcode
, equals
. if overrides these, you'll need fix implementation.
you'll find great guidelines proving proper implementation on eric lippert's blog post guidelines , rules gethashcode.
in case, guideline seems missing current implementation:
guideline: integer returned gethashcode should never change
ideally, hash code of mutable object should computed fields cannot mutate, , therefore hash value of object same entire lifetime.
Comments
Post a Comment