Introduce Using Statement

Creates a new Using statement for IDisposable variable, and removes a Dispose() call.

Availability

Available from the context menu or via shortcuts:

  • when the edit cursor or caret is on a variable declaration. The variable type should implement IDisposable.
  • when the selection contains a variable declaration and all references to it. The variable type should implement IDisposable.

Example

public void DrawEllipses(int count,
  int diameter,
  Color color,
  Graphics graphics,
  Rectangle area)
{
  Pen pen = new Pen(color);
  for (int i = 0; i < count; i++)
    graphics.DrawEllipse(pen, GenerateEllipseRectangle(diameter, area));
}
Public Sub DrawEllipses(ByVal count As Integer,
                        ByVal diameter As Integer,
                        ByVal color As Color,
                        ByVal graphics As Graphics,
                        ByVal area As Rectangle)
  Dim pen As Pen = New Pen(color)
  Dim i As Integer = 0
  While i < count
    graphics.DrawEllipse(pen, GenerateEllipseRectangle(diameter, area))
    i += 1
  End While
End Sub

Result:

public void DrawEllipses(int count,
  int diameter,
  Color color,
  Graphics graphics,
  Rectangle area)
{
  using (Pen pen = new Pen(color))
  {
    for (int i = 0; i < count; i++)
      graphics.DrawEllipse(pen, GenerateEllipseRectangle(diameter, area));
  }
}
Public Sub DrawEllipses(ByVal count As Integer,
                        ByVal diameter As Integer,
                        ByVal color As Color,
                        ByVal graphics As Graphics,
                        ByVal area As Rectangle)
    Using pen As Pen = New Pen(color)
      Dim i As Integer = 0
      While i < count
        graphics.DrawEllipse(pen, GenerateEllipseRectangle(diameter, area))
        i += 1
      End While
    End Using
End Sub