Re: Optimal use of foreach

Sébastien Lorion <[email protected]>
Newsgroups gmane.comp.windows.devel.dotnet.advanced
Message-ID <[email protected]>
When you use foreach, it actually calls myDictionary.Keys.GetEnumerator()
which returns a new instance of IEnumerator<T>. That enumerator is then used
during the loop and Keys is never called again. Open up Reflector and take a
look at the code, you will better understand what's going on this way ;)

for loops are usually used in inner loops where you don't want to create
millions of new IEnumerator<T>. They are also slightly faster on arrays, but
the vast majority of the time, foreach is fine and makes the code clearer.

Sébastien
On Tue, Jan 27, 2009 at 8:43 PM, Mont Rothstein <[email protected]>wrote:

> When using foreach if the collection is a property will it be called on
> each
> pass or only once?
>
> Can I do:
>
> foreach (string key in myDictionary.Keys)
> {
> }
>
> or will that call Keys each time, therefore requiring that I do:
>
> Dictionary<string, string>.KeysCollections keys;
>
> keys = myDictionary.Keys;
>
> foreach (string key in keys)
> {
> }
>
> Thanks,
> -Mont
>
> ===================================
> View archives and manage your subscription(s) at
> http://peach.ease.lsoft.com/archives
>

===================================
View archives and manage your subscription(s) at http://peach.ease.lsoft.com/archives
lmpx.com only provides a reader for public news (NNTP) servers. It is not affiliated with the servers or forums shown here and is not responsible for the content of articles, which is written by their respective authors.