Thanks for all the info. Never thought I would spark such an interesting
discussion. In my case, I am using this to read values out of a config file.
I prefer using a foreach over a for loop when ever I can.
The following is in need of exception handling but given all that I have
learned, I would choose this over a more "manual" approach.
<appSettings>
<add key="MachineIDs" value="44,3,43,566" />
</appSettings>
private int[] GetConfigIntArray(string key)
{
string[] values = ConfigurationManager.AppSettings[key].Split(',');
return Array.ConvertAll<string, int>(values, delegate(string s) { return
int.Parse(s); });
}
Thanks,
-Andrew
[quoted text, click to view] "Jon Skeet [C# MVP]" <skeet@pobox.com> wrote in message
news:1140170997.629553.115900@g43g2000cwa.googlegroups.com...
> Marc Gravell wrote:
>> I'm not sure it's that different either way; in the anonymous delegate
>> you
>> would still have access to e.g. any error collection etc that is scoped
>> by
>> the containing method, or any class members like events.
>
> I was thinking about that - and there's *one* difference which springs
> to mind. If you use a plain for loop with an index, you get to know the
> *indexes* of which elements are invalid (or whatever). If you use
> foreach or the collection methods, you only get to know the *values*.
> Sometimes the indexes could be important (eg to highlight invalid rows
> in a UI).
>
>> Because of this, in a scenario like this the only thing that would make
>> me
>> choose one over the other is performance; I remember a chain a little
>> while
>> ago (here) comparing foreach, ForEach and indexer based access :
>> embarrasingly I can't remember which one won ;-(
>
> See
>
http://msmvps.com/blogs/jon.skeet/archive/2006/01/20/foreachperf.aspx
>
> I would expect even the reasonably cheap operation of parsing integers
> to dwarf the iteration performance.
>
> Unless you have a good reason to believe that performance is
> particularly important in a given situation, it's one of the *last*
> reasons I would use to choose one over the other. I'd go for simplicity
> and readability primarily - and that will depend on what error handling
> is required etc.
>
> Jon
>