Consolidate Conditional Blocks

Consolidates a conditional statement containing two for-loops inside each of its if and else blocks into a single for-loop containing the conditional, with the previous contents of the for-loops now moved into the if and else blocks of the conditional.

Availability

Available from the context menu or via shortcuts:

  • when the caret is on the if keyword of a conditional statement containing two for-loops inside each of its if and else blocks.

Examples

public string[] Lines { get; set; }
public void AddStringToLines(string value, bool isPrefix)
{if (isPrefix)
    for (int i = 0; i < Lines.Length; i++)
      Lines[i] = value + Lines[i];
  else
    for (int i = 0; i < Lines.Length; i++)
      Lines[i] += value;
}
Public Property Lines() As String()
Public Sub AddStringToLines(ByVal value As String, ByVal isPrefix As Boolean)If isPrefix Then
    For i As Integer = 0 To Lines.Length
      Lines(i) = value + Lines(i)
    Next i
  Else
    For i As Integer = 0 To Lines.Length
      Lines(i) += value
    Next i
  End If
End Sub

Result:

public string[] Lines { get; set; }
public void AddStringToLines(string value, bool isPrefix)
{
  for (int i = 0; i < Lines.Length; i++)
    if (isPrefix)
      Lines[i] = value + Lines[i];
    else
      Lines[i] += value;
}
Public Property Lines() As String()
Public Sub AddStringToLines(ByVal value As String, ByVal isPrefix As Boolean)
  For i As Integer = 0 To Lines.Length
    If isPrefix Then
      Lines(i) = value + Lines(i)
    Else
      Lines(i) += value
    End If
  Next
End Sub

Screenshot

CSharpConsolidateConditionalBlocks