Item 11: Prefer foreach Loops

The C# foreach statement generates the best iteration code for any collection you have. Examine these three loops:

int[] foo = new int[100]

//Loop 1
foreach (int i in foo)
    Console.Write(i.ToString());

//Loop 2
for (int i = 0; i < foo.Length; i++)
    Console.Write(i.ToString());

//Loop 3
int i = foo.Length;
for (int j = 0; j < i; j++)
    Console.Write(foo[j].ToString());

For the current and future C# compilers (version 1.1 and up), loop 1 is the best. It's even less typing so productivity is also better. Note: The C# 1.0 compiler produced much slower code for loop 1, so loop 2 is the best in that version. By moving the "Length" variable out of the loop, you make a change that hinders the JIT compler's chance to remove range checking inside the loop.

Loop 3 is the worst...the CLR guarantees that you cannot write code that overruns the memory your variables own. The runtime generates a test of the actual array bounds (not the "i" variable) before accessing each particular array element. You are now forcing the runtime to check the array index on every loop!

Loop 1 is better than Loop 2 because you allow the compiler to check the upper and lower bounds. Some people still believe index variables start at 1, not 0. Loop 2 forces you to know the lower bound, whereas Loop 1 does the work for you.

Custom objects/types: foreach allows you and your users to iterate across members if you support the .NET environment's rules for a collection.

These are just a few reasons why...to read more, pick up "Effective C#: 50 Specific Ways to Improve Your C#" by Bill Wagner.

You can buy it at the Addison-Wesley website: http://www.aw-bc.com/