What I like to do is declare objects without initializing them, but set their default values to Nothing . Then, at the end of the cycle, I write:
If anObject IsNot Nothing Then anObject.Dispose()
Here is a complete example:
Public Sub Example() Dim inputPdf As PdfReader = Nothing, inputDoc As Document = Nothing, outputWriter As PdfWriter = Nothing 'code goes here that may or may not end up using all three objects, ' such as when I see that there aren't enough pages in the pdf once I open ' the pdfreader and then abort by jumping to my cleanup routine using a goto .. GoodExit: If inputPdf IsNot Nothing Then inputPdf.Dispose() If inputDoc IsNot Nothing Then inputDoc.Dispose() If outputWriter IsNot Nothing Then outputWriter.Dispose() End Sub
This is also great for placing your main objects at the top of the routine, using them inside the Try procedure, and then deleting them in the Finally block:
Private Sub Test() Dim aForm As System.Windows.Forms.Form = Nothing Try Dim sName As String = aForm.Name 'null ref should occur Catch ex As Exception 'got null exception, no doubt Finally 'proper disposal occurs, error or no error, initialized or not.. If aForm IsNot Nothing Then aForm.Dispose() End Try End Sub
JeffreyDurham Dec 07 '13 at 20:43 2013-12-07 20:43
source share