Can you Return out of a Using...End Using block?

Administrator

VB.NET Forum Admin
Joined
Jun 3, 2004
Messages
1,462
Programming Experience
10+
If I have code such as:

VB.NET:
Public Function GetAnswer() as String
      Using Connection As New SQLConnection(...)
            ...some code here
            Return TheAnswer
      End Using
End Function

Is there any impact in "returning" out of a Using..End Using block? In other words, is the connection automatically closed and disposed if I return out of the block (back to the function)? I'm curious if it ever gets to End Using if you return from within the block. The alternative of course is to use the old code method of GetAnswer=Value and then it will return the result that way.
 
Can you set TheAnswer in the Using block and return it outside?

VB.NET:
Public Function GetAnswer() as String
      Dim TheAnswer As String

      Using Connection As New SQLConnection(...)
            ...some code here
            TheAnswer = "Hello"
      End Using

      Return TheAnswer
End Function

Of course you may have to do some additional checks to determine what the function should return if an error occurs in the Using block.

CT
 
"Using" calls Dispose on the used object instance no matter how you exit the block. In this case (SqlConnection) Dispose method also calls for Close on the connection.
 
If I have code such as:

VB.NET:
Public Function GetAnswer() as String
      Using Connection As New SQLConnection(...)
            ...some code here
            Return TheAnswer
      End Using
End Function

Is there any impact in "returning" out of a Using..End Using block? In other words, is the connection automatically closed and disposed if I return out of the block (back to the function)? I'm curious if it ever gets to End Using if you return from within the block. The alternative of course is to use the old code method of GetAnswer=Value and then it will return the result that way.

Given that a Using block is shorthand for (based on your code):

VB.NET:
Dim connection As New SqlConnection(...)
Try
   ...some code here
  Return theAnswer
Finally
  connection .Dispose()
End Try
Then yep, i'd say returning from the block disposes of the variable
 
Back
Top