Skip to main content

ForEach Action can be called

In This Article

CodeRush Classic shows the ForEach Action can be called code issue for foreach statements iterating through a list or an array.

#Fix

Convert a foreach loop body into a method and replace this loop with the appropriate ForEach method call.

#Purpose

The use of the Array.ForEach method makes your code more readable.

#Example

public static IEnumerable GetPositiveValues(this int[] intArray)
{
    List<int> result = new List<int>();foreach (int value in intArray)
        if (value > 0)
            result.Add(value);
    return result;
}

Fix:

public static IEnumerable GetPositiveValues(this int[] intArray)
{
    List<int> result = new List<int>();
    Array.ForEach(intArray, value =>{ if (value > 0)
            result.Add(value);});
    return result;
}