Skip to main content

ForEach to For/For to ForEach

  • 2 minutes to read

Purpose

This Refactoring is used to switch between the for loop and foreach loop. The foreach loop is more readable and compact. On the other hand, if your algorithm uses the iteration number for calculations, the for loop is more applicable.

Note

In rare cases, the ForEach to For refactoring may change your code’s external behavior if the IEnumerator implementation causes significant side effects, or if any of the IEnumerator members behave in a non-standard manner.

Availability

Available when the caret is on the for or foreach keyword.

Usage

  1. Place the caret on a foreach keyword.

    Note

    The blinking cursor shows the caret’s position at which the Refactoring is available.

    string result = String.Empty;
    foreach (string str in strings)
        if (str.Length > 2) 
            result += $"{str} ";
    
  2. Press the Ctrl + . or Ctrl + ~ shortcut to invoke the Code Actions menu.
  3. Select ForEach to For from the menu (For to ForEach if you are converting the for loop to foreach loop).

After execution, the Refactoring converts the foreach loop to a for loop or vice versa.

string result = String.Empty;
for (int i = 0; i < strings.Count; i++)
    if (strings[i].Length > 2)
        result += $"{strings[i]} ";
See Also