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?
These classes need to dispose of these objects. I created a virtual Dispose method in the base ScreenObject base class and then implemented an override Dispose method in each of the derived classes that hold onto unmanaged resources.
In the context of C#, dispose is an object method invoked to execute code required for memory cleanup and release and reset unmanaged resources, such as file handles and database connections.
The Dispose() method The Dispose method performs all object cleanup, so the garbage collector no longer needs to call the objects' Object. Finalize override. Therefore, the call to the SuppressFinalize method prevents the garbage collector from running the finalizer.
You should take advantage of the Dispose/Finalize pattern only when it is needed. To be more precise, you should use it only when your type invokes unmanaged code that allocates unmanaged resources (including unmanaged memory) and then it returns a handle that you must use eventually to release the resource.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With