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?
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
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With