Back to Devexpress

ForEach to For/For to ForEach

coderushforroslyn-115530-refactoring-assistance-foreach-to-for-for-to-foreach.md

latest1.5 KB
Original Source

ForEach to For/For to ForEach

  • Aug 03, 2020
  • 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.

  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.

csharp
string result = String.Empty;
for (int i = 0; i < strings.Count; i++)
    if (strings[i].Length > 2)
        result += $"{strings[i]} ";
vb
Dim result As String = String.Empty
For i As Integer = 0 To Strings.Count - 1
    If Strings(i).Length > 2 Then
        result &= $"{Strings(i)} "
    End If
Next i

See Also

ForEach to Linq