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
  • 92,468
  • 14
  • 98
  • 151
CSharpNewBee
  • 1,871
  • 6
  • 26
  • 61

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
  • 976,458
  • 251
  • 2,474
  • 2,830
1

There's nothing wrong with it.

Just two suggestions:

Community
  • 1
  • 1
TTT
  • 1,738
  • 2
  • 26
  • 55
  • 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