3

I know that you should always call dispose on modal forms. However, I have a related question.

If I have a method in my application like

Private Sub tempMethod

Dim expForm as new ExplorerForm(tempDataTable)
expForm.ShowDialog

'Should I call dispose here?
'or would the form be automatically disposed when it goes out of scope
'after this method exits?

End Sub
swiftgp
  • 997
  • 1
  • 9
  • 17
  • 1
    _"However, if you do form1.ShowDialog() to show the form modally, the form will not be disposed, and you'll need to call form1.Dispose() yourself. I believe this is the only time you should worry about disposing the form yourself."_ http://stackoverflow.com/a/3097383/284240 – Tim Schmelter Jul 26 '12 at 21:46
  • @TimSchmelter - That question answers this one, but isn't a duplicate, so it's unlikely this will get closed as a dupe... I'd say you should post that as an answer rather than a comment. You'd get my vote. – David Jul 26 '12 at 21:53
  • @TimSchmelter - I don't think that answers the OP question. The OP knows that Dispose should be called manually, OP just wanted to know if it would happen if the form fell out of scope at the end of the method. – Chris Dunaway Jul 27 '12 at 14:44
  • @ChrisDunaway: I've commented it in the first place, because i wasn't sure if it answers or even could help but it was related for sure. Then i've answered that comment (+ `using-statement` hint as you) and got 2 downvotes. So now i keep it as comment, it might help someone in future ;) – Tim Schmelter Jul 27 '12 at 15:04

1 Answers1

3

When the form goes out of scope, it will be garbage collected at some point in the future and Dispose will be called then, but it's better to use the Using keyword in this instance:

Private Sub tempMethod
    Using expForm As New ExplorerForm(tempDataTable)
        expForm.ShowDialog()

        'Other code here
    End Using      'Form disposed here
End Sub
Chris Dunaway
  • 10,974
  • 4
  • 36
  • 48