Code inspection: For-loop can be converted into foreach-loop
When you iterate through a collection without modifying it or accessing the iteration variable, it is possible to use foreach
instead of the for
loop. The main benefit of the foreach
loop is that it allows creation of methods that can work with different collection types. The foreach
loop supports any type that implements the IEnumerable<T>
interface (in fact, any type that has the GetEnumerator
method). In addition, using foreach
allows work with LINQ query results because many LINQ providers return query results as IEnumerable<T>
.
If you have a method that iterates a List
in the for
loop, one day you might decide to make your method work with other collection types. Then you will need to use foreach
to be able to iterate IEnumerable<T>
objects.
In the example below, ReSharper determines that it is possible to use foreach
instead of for
and suggests doing so:
In other words, a method can be used with a wider range of collection types if you use foreach
because you can pass IEnumerable<T>
to it. Below is a simple example of such a method: