Are there multiple iterations of IEnumerable in this code?
public static IEnumerable<T> ForEach<T>(this IEnumerable<T> source, Action<T> action)
{
foreach (var element in source) action(element);
return source;
}
The above code is giving me a warning that the source is potentially repeated multiple times, but is it really? It repeats once in the foreach statement, but how does return it itated again?
source to share
In the current code, you are showing that there is only one iteration. It is possible that you will list it again somewhere else, since the same enumerable is returned. This is what warns you.
My personal preference is to change the return type ForEach
to void
and add a second one that returns the result Func<T, R>
.
So:
public static void ForEach<T>(this IEnumerable<T> source, Action<T> action)
{
foreach (var element in source)
action(element);
}
and
public static IEnumerable<R> ForEach<T, R>(this IEnumerable<T> source, Func<T, R> action)
{
foreach (var element in source)
yield return action(element);
}
This way you will never reuse the same enum, and you make it lazy: it will not execute before you actually call the enum.
source to share