Monday, March 20, 2006

foreach vs for

Evidence:Quote from: Effective C#: 50 Specific Ways to Improve Your C# , By Bill WagnerThe C# foreach statement is more than just a variation of the do, while, or for loops. It generates the best iteration code for any collection you have. Its definition is tied to the collection interfaces in the .NET Framework, and the C# compiler generates the best code for the particular type of collection. When you iterate collections, use foreach instead of other looping constructs.

MSDN Web site states: http://msdn.microsoft.com/library/default.asp?url=/library/en-us/dnpag/html/scalenetchapt05.asp
Additional investigations by Brad Abrams: http://blogs.msdn.com/brada/archive/2004/04/29/123105.aspx

Use foreach unless you have a very good reason not to.

No comments: