In the Enumerator example you are not disposing the Enumerator, it a good practice to do it, aslo foreach will do it for you (I think this wasn't so in old versiosn though). Also foreach will use IEnumerable<T> and IEnumerator<T> if they are available (As pointed by Cerberus), which will have the performance benefit of generics over late binding (an potential box un-box). And lastly, of course it's meant to be more readable.
There an extra bonus, that is if you have already a foreach it will be easier to change it to run in parallel, by changing it to Parallel.ForEach. On 1 ago, 21:15, John Smith <[email protected]> wrote: > I am a beginner of C# .NET. Found the following code snippet > onhttp://msdn.microsoft.com/en-us/library/system.collections.dictionary... > > 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(); > }
