Reputation: 23
Can anyone tell me why is a IDictionaryEnumerator preferred for looping a HashTable.
How is it different from IEnumerator although it is derived from it?
When to use which?
Upvotes: 2
Views: 1219
Reputation: 1062492
The point is that a hashtable/dictionary enumerates pairs, with a .Key
and .Value
. This is a bit moot from 2.0, since Dictionary<TKey,TValue>
implements IEnumerable<KeyValuePair<TKey, TValue>>
which is clearer.
This interface simply makes it more convenient to access the key/value in a few cases.
You can achieve the same in Hashtable
(without using IDictionaryEnumerator
) via:
foreach(DictionaryEntry pair in hashTable) {
.... use pair.Key and pair.Value
}
Upvotes: 7
Reputation: 13676
IDictionaryEnumerator is specially designed for enumerating over collections of key/value pairs. It gives you access to the key and value of the current entry (among other things, as seen in the documentation). IEnumerator would only give you the current value.
Upvotes: 0
Reputation: 74802
IDictionaryEnumerator allows you to access both the key and the value of the current entry. As you note, an IDictionaryEnumerator is an IEnumerator, so if you're just using it in a foreach, you'll only notice this because the range variable is a DictionaryEntry; but if you're working with the IDictionaryEnumerator manually, you'll find it has Key and Value properties as well as Current.
It's not so much that it is 'preferred' for looping a Hashtable -- it's just that if you enumerate a Hashtable, you're enumerating key-value pairs, not just values, and the IDictionaryEnumerator represents that.
Upvotes: 4