ReSharper 2024.1 Help

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:

public void ViewCategories(List<string> categories) { for (int i = 0; i < categories.Count; i++) { Console.WriteLine(categories[i]); } }
public void ViewCategories(List<string> categories) { foreach (string c in categories) { Console.WriteLine(c); } }

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:

public void ViewCategories(IEnumerable<string> mycollection) { foreach (var s in mycollection) { Console.WriteLine(s); } }
Last modified: 08 April 2024