1

I'm writing a code and I have a situation like this:

Sub Example()
    Using DT As New DataTable
        '...some code
        If mCondition = True Then GoTo Other
        '...some code
    End Using
Other:
    '...some code
End Sub

I'm worried about the consequences of "goto" on the block "Using": does it work correctly?

Do I need to use a different code structure? (or is better if I do so)

Matt Wilko
  • 26,994
  • 10
  • 93
  • 143
genespos
  • 3,211
  • 6
  • 38
  • 70
  • a better solution might be to extract this as a method and, when `mCondition = 1` return? It's hard to say without a complete code example – default Nov 18 '15 at 10:21
  • You are worrying about the wrong thing: it is the `GoTo` that makes experienced programmers nervous if they look at this, not exiting the `Using` block! See Matt Wilko's answer. – AAT Nov 18 '15 at 10:27

1 Answers1

1

You don't have to worry about existing out of a Using block because the compiler will handle the disposing of resources as soon as control flow moves out of the block.

From The documentation:

"A Using block behaves like a Try...Finally construction in which the Try block uses the resources and the Finally block disposes of them. Because of this, the Using block guarantees disposal of the resources, no matter how you exit the block. This is true even in the case of an unhandled exception, except for a StackOverflowException."

So your code is effectively behaving like this:

Sub Example()
    Dim DT As New DataTable
    Try
        '...some code
        If mCondition = True Then GoTo Other
        '...some code
    Finally
        DT.Dispose
    End Try
Other:
    '...some code
End Sub

Having said that, having a goto in the first place is almost always a code smell, so you could do with refactoring in some way. See: GoTo statements and alternatives in VB.NET

Community
  • 1
  • 1
Matt Wilko
  • 26,994
  • 10
  • 93
  • 143
  • Thanks. I saw the hints in the link posted by you and I'll remove some "GoTo" from my code, but (at the moment) I'm not able to figure how to remove the ones who are in the middle of a block. I'll study ... ;) – genespos Nov 18 '15 at 10:29
  • @genespos but I just gave you an example of how to do it. What was wrong with extracting a method of it? – default Nov 18 '15 at 10:43
  • No problems with your example, I was talking about what I've read in the link you gave me. – genespos Nov 18 '15 at 10:53