Is the ever any circumstances, when the following:
public IEnumerable<Foo> Foobar (Bar bar)
{
List<Foo> result = new List<Foo>()
foreach(var Qux in bar.QuxSource)
{
Foo item;
... //a procudure that is intricate enough not to be clearly repressentable with a LINQ method
result.Add(item);
... //The aforementioned inticate proceduce continues. Possiblily adding more items to result
}
return result;
}
Is preferable to:
public IEnumerable<Foo> Foobar (Bar bar)
{
foreach(var Qux in bar.QuxSource)
{
Foo item;
... //a procudure that is intricate enough not to be clearly repressentable with a LINQ method
yield return item;
... //The aforementioned inticate proceduce continues. Possiblily yielding more items
}
}
I mean the later is clearly wonderful.
With the glory of defered operation, if i only use Foobar(someBar).First(), it doesn’t have togenerate the all the returned items.
I see the former used alot, particulary by experienced coders. (Who I guess aren’t uptodate with list comprehesions in modern C#).
So is the former patern better undersome cercumstances?
(looking only at library code, targetted at reuse)
I’m thinking maybe when being able to produce the items is dependent on some external resource such as having a file open.
What is the use case foreach?
I’m guess it
Your example use case is correct, but more generally you’d probably want to adopt the former pattern if: