8

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

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

Visual studio doesn't complain about this, nor does Resharper, however, before I continue to use this approach, I want to reach out and check if it is a recommended approach.

Jon Limjap
  • 94,284
  • 15
  • 101
  • 152
CSharpNewBee
  • 1,951
  • 6
  • 28
  • 64

2 Answers2

11

There's nothing wrong with that. The method will only be evaluated once.

It is basically:

using(var iter = GetItemDetails(item).GetEnumerator())
{
    while(iter.MoveNext()
    {
        var item = iter.Current;
        // ...
    }
}
Marc Gravell
  • 1,026,079
  • 266
  • 2,566
  • 2,900
1

There's nothing wrong with it.

Just two suggestions:

Community
  • 1
  • 1
TTT
  • 1,848
  • 2
  • 30
  • 60
  • the times when `List.ForEach` would be preferable to regular `foreach` are *minute* - not least, keep in mind that `List` has a custom `struct` iterator, making it pretty damned efficient. And re `for` vs `foreach`, that is **hugely** dependent on the scenario, and usually makes very little difference. The difference in most *actual doing stuff* code is so small that you're essentially just profiling your profiler. – Marc Gravell Jan 29 '14 at 14:47
  • Thank you. Maybe it's because English is not my mother language, but there is something I'm not sure to get in your first sentence. I did not mention .ForEach() for performance reason, just for readability. If agree about the for loop, that why I mentionned "may happen even in C#", but I have already encountered specific cases in which this kind of optimization proved to be useful. – TTT Jan 29 '14 at 15:10