I am a beginner of C# .NET. Found the following code snippet on
http://msdn.microsoft.com/en-us/library/system.collections.dictionarybase.aspx
What are some examples / use cases where the use of enumerator is
preferrable over foreach?
Thanks.
// Uses the foreach statement which hides the complexity of the
enumerator.
// NOTE: The foreach statement is the preferred way of enumerating
the contents of a collection.
public static void PrintKeysAndValues1( ShortStringDictionary
myCol ) {
foreach ( DictionaryEntry myDE in myCol )
Console.WriteLine( " {0,-5} : {1}", myDE.Key, myDE.Value );
Console.WriteLine();
}
// Uses the enumerator.
// NOTE: The foreach statement is the preferred way of enumerating
the contents of a collection.
public static void PrintKeysAndValues2( ShortStringDictionary
myCol ) {
DictionaryEntry myDE;
System.Collections.IEnumerator myEnumerator =
myCol.GetEnumerator();
while ( myEnumerator.MoveNext() )
if ( myEnumerator.Current != null ) {
myDE = (DictionaryEntry) myEnumerator.Current;
Console.WriteLine( " {0,-5} : {1}", myDE.Key,
myDE.Value );
}
Console.WriteLine();
}