Home All Groups Group Topic Archive Search About

Problem with Dictionary<T,U>.Keys enumerator returning invalid keys

Author
5 Jun 2006 7:21 PM
Brian Richards
I'm experiencing some wierd behavior with a Dictionary<T,U> class using
foreach loops, such that the Key returned in the foreach is not contained in
the dictionary.

code:

Dictionary<A, B> dict;
.....
foreach(A key in dict.Keys)
{
    bool foo = dict.ContainsKey(A); //returning false
}

Does anyone know what kinds of circumstances could cause this?

Author
5 Jun 2006 8:54 PM
Carl Daniel [VC++ MVP]
Show quote
"Brian Richards" <bricha***@gmail.com> wrote in message
news:uJUkCWNiGHA.4044@TK2MSFTNGP03.phx.gbl...
> I'm experiencing some wierd behavior with a Dictionary<T,U> class using
> foreach loops, such that the Key returned in the foreach is not contained
> in
> the dictionary.
>
> code:
>
> Dictionary<A, B> dict;
> ....
> foreach(A key in dict.Keys)
> {
>    bool foo = dict.ContainsKey(A); //returning false
> }
>
> Does anyone know what kinds of circumstances could cause this?

What's the type of the key?

If the key is a user defined type that doens't implement equality correctly,
it's possible that you'd get keys back from the enumerator that can't be
found in the dictionary.

-cd
Author
10 Jun 2006 2:09 AM
SP
Show quote
"Brian Richards" <bricha***@gmail.com> wrote in message
news:uJUkCWNiGHA.4044@TK2MSFTNGP03.phx.gbl...
> I'm experiencing some wierd behavior with a Dictionary<T,U> class using
> foreach loops, such that the Key returned in the foreach is not contained
> in
> the dictionary.
>
> code:
>
> Dictionary<A, B> dict;
> ....
> foreach(A key in dict.Keys)
> {
>    bool foo = dict.ContainsKey(A); //returning false

    shouldn't that be  bool foo = dict.ContainsKey(key);

SP

Show quote
> }
>
> Does anyone know what kinds of circumstances could cause this?
>
>

AddThis Social Bookmark Button