V3191. Iteration through collection makes no sense because it is always empty.
The analyzer has detected an attempt to iterate through an empty collection. This operation makes no sense: probably, there is an error in the code.
Let's look at the example:
private List<Action> _actions;
....
public void Execute()
{
var remove = new List<Action>();
foreach (var action in _actions)
{
try
{
action.Invoke();
}
catch (Exception ex)
{
Logger.LogError(string.Format("Error invoking action:\n{0}", ex));
}
}
foreach (var action in remove)
_actions.Remove(action);
}
The 'Execute' method invokes delegates from the '_actions' list one by one. It also catches and logs errors that occur during the method execution. In addition to the main loop, there is another one at the end of the method. The loop should remove the delegates that are stored in the 'remove' collection from the '_actions' list.
The issue is that the 'remove' collection will always be empty. It is created at the beginning of the method, but is not filled during the method's execution. Thus, the last loop will never be executed.
The correct method's implementation may look like this:
public void Execute()
{
var remove = new List<Action>();
foreach (var action in _actions)
{
try
{
action.Invoke();
}
catch (Exception ex)
{
Logger.LogError(string.Format("Error invoking action:\n{0}", ex));
remove.Add(action);
}
}
foreach (var action in remove)
_actions.Remove(action);
}
Now we add the delegates that caused exceptions to the 'remove' collection, so that we can remove them later.
The analyzer may issue a warning for a method call that iterates through a collection.
Look at another example:
int ProcessValues(int[][] valuesCollection,
out List<int> extremums)
{
extremums = new List<int>();
foreach (var values in valuesCollection)
{
SetStateAccordingToValues(values);
}
return extremums.Sum();
}
The 'ProcessValues' method takes arrays of numbers for processing. In this case, we are interested in the 'extremums' collection: it is created empty and is not filled during the method execution. 'ProcessValues' returns the result of calling the 'Sum' method on the 'extremums' collection. The code looks wrong because calling 'Sum' always returns 0.
The correct method's implementation may look as follows:
int ProcessValues(int[][] valuesCollection,
out List<int> extremums)
{
extremums = new List<int>();
foreach (var values in valuesCollection)
{
SetStateAccordingToValues(values);
extremums.Add(values.Max());
}
return extremums.Sum();
}