Method call in foreach declaration

I have a foreach that calls a method to get its collection.

foreach(var item in GetItemDetails(item)) { } 

Visual Studio does not complain about this, and Resharper, however, before I continue to use this approach, I want to contact and check if this is the recommended approach.

+8
c # foreach
source share
2 answers

There is nothing wrong. The method will be evaluated only once.

This is basically:

 using(var iter = GetItemDetails(item).GetEnumerator()) { while(iter.MoveNext() { var item = iter.Current; // ... } } 
+11
source share

There is nothing wrong.

Only two sentences:

  • If what you put in the loop can be written as a method for individual elements, which makes it reusable, I will also consider List.ForEach(...); . Info: http://msdn.microsoft.com/en-us/library/bwabdf9z%28v=vs.110%29.aspx

  • If you really will be in a performance state (which can even happen in C #), the for loop is usually the fastest, although less readable, less compressed code: Info: In .NET, which loop is faster, 'for' or ' foreach '?

+1
source share

All Articles