The problem is that you are relying on the non-generic IEnumerator
interface, which doesn't reveal the real element-type (its Current
property is of type object
). Use the generic interface (IEnumerator<T>
, which does make the element-type easily discoverable) instead, and you will be fine.
Of course, you don't need any special effort for this. The Dictionary<,>
class implements the IEnumerable
interface explicitly. Its 'implicit' GetEnumerator
method returns an enumerator that is strongly typed (a nested type that implements the generic interface), which is what we want.
So it's fine to use implicit typing all the way and let the compiler figure things out.
// Actually a Dictionary<string, cAsso>.Enumerator
// which in turn is an IEnumerator<KeyValuePair<string, cAsso>>
using(var iterdico = mDico.GetEnumerator())
{
while (iterdico.MoveNext())
{
// var = KeyValuePair<string, cAsso>
var kvp = iterdico.Current;
// var = string
var key = kvp.Key;
// var = cAsso
var value = kvp.Value;
...
}
}
EDIT:
A few other peripheral points:
- In general, you should
Dispose
of enumerators, typically with a using
block.
- The use of the
Reset
method on enumerators is not recommended. In fact, in this particular case, it is useless.
- Note that the element-type of the dictionary's enumerator is a Key-Value pair, not the value itself. if you are only interested in the values, enumerate the sequence returned by the dictionary's
Value
property.
- As Davide Piras points out, in most cases, you just want a normal
foreach
loop instead of messing around with the enumerator yourself.