Skip to main content

Using to Try/Finally

Converts a using statement to a try/finally block.

#Availability

Available from the context menu or via shortcuts:

  • when the caret is on a using statement.

#Notes

  • The using statement is replaced with a variable initialization.
  • The body of the using block is moved into the try block
  • The finally block contains variable disposal code.

#Example

using (FileStream lFS = new FileStream("", FileMode.CreateNew))
{
    lFS.SetLength(100);
    lFS.Flush();
    lFS.Close();
}
Dim lFS As FileStream = New FileStream("", FileMode.Create)
Using lFS
    lFS.SetLength(100)
    lFS.Flush()
    lFS.Close()
End Using

Result:

FileStream lFS = new FileStream("", FileMode.CreateNew);
try
{
    lFS.SetLength(100);
    lFS.Flush();
    lFS.Close();
}
finally
{
    if (lFS != null)
        lFS.Dispose();
}
Dim lFS As FileStream = New FileStream("", FileMode.Create)
Try
    lFS.SetLength(100)
    lFS.Flush()
    lFS.Close()
Finally
    If lFS IsNot Nothing Then
        lFS.Dispose()
    End If
End Try

#Animation

rsUsingToTryFinallyCSharp