Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

IEnumerator for HashTable?

Tags:

c#

linq

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?

like image 798
AdamFo Avatar asked May 25 '26 04:05

AdamFo


2 Answers

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
}
like image 128
Marc Gravell Avatar answered May 31 '26 08:05

Marc Gravell


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.

like image 21
itowlson Avatar answered May 31 '26 09:05

itowlson