Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

.NET - Does Return prevent objects disposing [duplicate]

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?

like image 574
AGB Avatar asked Mar 12 '13 11:03

AGB


People also ask

How to override Dispose method in c#?

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.

How does Dispose work in c#?

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.

How Dispose method works in. net?

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.

When to Dispose c#?

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.


1 Answers

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.

like image 126
Jon Skeet Avatar answered Oct 04 '22 09:10

Jon Skeet