
This is the Title of the Book, eMatter Edition
Copyright © 2007 O’Reilly & Associates, Inc. All rights reserved.
Constraining Type Arguments
|
275
{
Console.WriteLine("key " + kvp.Key);
Console.WriteLine("Value " + kvp.Value);
}
Discussion
The nongeneric System.Collections.Hashtable (the counterpart to the System.
Collections.Generic.Dictionary
class), System.Collections.CollectionBase, and
System.Collections.SortedList classes support foreach using the DictionaryEntry
type as shown here:
foreach (DictionaryEntry de in myDict)
{
Console.WriteLine("key " + de.Key);
Console.WriteLine("Value " + de.Value);
}
However, the Dictionary object supports the KeyValuePair<T,U> type when using a
foreach loop. This is due to the fact that the GetEnumerator method returns an
IEnumerator, which in turn returns KeyValuePair<T,U> types, not DictionaryEntry
types.
The
KeyValuePair<T,U> type is well suited to be used when enumerating the generic
Dictionary class with a foreach loop. The DictionaryEntry object contains key and
value pairs as objects, whereas the
KeyValuePair<T,U> type contains key and value
pairs as their original types, defined when creating the
Dictionary object. This boosts
performance and can reduce the amount of code you have to write, as you do not
have to cast the key and value pairs to their original types.
See Also
See the “System.Collections.Generic.Dictionary Class,” “System.Collections.Generic.
SortedList ...