The consensus on best practice for resource-intensive operations, such as opening database connections, seems to be to use Using blocks, because the Using block "guarantees disposal of the resource... even in the case of an unhandled exception.".
Here is how most examples I've found are written:
Sub ExecuteCommand(ByVal sql As String, ByVal connectionString As String)
Using connection As New SqlConnection(connectionString)
Dim command As New SqlCommand(sql, connection)
command.Connection.Open()
command.ExecuteNonQuery()
End Using
End Sub
But nested Using blocks are allowed, and I occasionally (but rarely) see the above written as:
Sub ExecuteCommand(ByVal sql As String, ByVal connectionString As String)
Using connection As New SqlConnection(connectionString)
Using command As New SqlCommand(sql, connection)
command.Connection.Open()
command.ExecuteNonQuery()
End Using
End Using
End Sub
My question: Is there any benefit to multiple nested Using blocks? Or does a single Using block already guarantee that all of the resources it contains will be disposed?
(Note: my code is in VB.NET, but the same question applies to C#.)
Usingsare very common in graphics related code where you might beUsinga Graphics object, a Brush, some Pens and a Bitmap at the same time.