5

Given the following code:

  Function GetSomething() As Integer
    Using dbConn As New SqlConnection("Connection_String")
      dbConn.Open()
      Using dbCmd As New SqlCommand(" SELECT SOMETHING ....", dbConn)
        Return Integer.Parse(dbCmd.ExecuteScalar())
      End Using
      dbConn.Close()
    End Using
  End Function

Will the Return prevent execution of the remainder of the function block i.e. the closing of the database connection and the implied Dispose() called when the Using block finishes?

AGB
  • 2,378
  • 21
  • 37

1 Answers1

14

No, a Using statement is equivalent to a Try/Finally statement - so the disposal is executed as execution leaves the block, whether that's by reaching the end of the block, returning normally, or via an exception.

You don't need the explicit Close call though, as you're disposing of the connection anyway.

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194