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?

+3


source to share


2 answers


The return does not iterate over the enum again. But you are returning it, and since the only way you could do BELOW with this result is to repeat it elsewhere, this warning is given.



Why return it if you're not going to repeat it later?

+4


source


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.

+1


source







All Articles