For to ForEach

Converts a for (For) loop to a foreach (ForEach) loop. Correctly infers type based on the object being iterated.

Availability

Available from the context menu or via shortcuts:

  • when the caret is on a for (For) keyword. The loop must iterate from zero to the index of the last element in an array or list.

Notes

  • For to ForEach automatically invokes Rename for the newly declared variable that references the current element.

Example

private string TestMethod(List<string> myStrings)
{
    string result = String.Empty;for (int i = 0; i &lt; myStrings.Count; i++)
        result += String.Format(".{0}", myStrings[i]);
    return result;
}
Private Function TestMethod(ByVal myStrings As List(Of String)) As String
    Dim result As String = String.EmptyFor i As Integer = 0 To myStrings.Count - 1 Step 1
        result += String.Format(".{0}", myStrings(i))
    Next
    Return result
End Function

Result:

private string TestMethod(List<string> myStrings)
{
    string result = String.Empty;
    foreach (string myString in myStrings)
        result += String.Format(".{0}", myString);
    return result;
}
Private Function TestMethod(ByVal myStrings As List(Of String)) As String
    Dim result As String = String.Empty
    For Each lMyString As String In myStrings
        result += String.Format(".{0}", lMyString)
    Next
    Return result
End Function

Screenshot

rsForToForeach

See Also