Do I need to use Dispose

James Buss 136 Reputation points
2021-01-09T17:08:47.77+00:00

When I need to quickly grab a piece of data, I usually write something like this:

Private Sub PopulateFilter()
        Dim Adapter As New OleDbDataAdapter("SELECT Max(ReceiptDate) AS LastReceiptDate FROM tblReceipts", My.Settings.ReceiptsConnectionString)
        Dim Data As New DataTable
        Adapter.Fill(Data)
        Me.ReceiptsBindingNavigatorYear.Tag = Year(Data(0)("LastReceiptDate"))
        Data.Dispose()
        Adapter.Dispose()
        Me.ReceiptsBindingNavigatorYear.Text = CStr(Me.ReceiptsBindingNavigatorYear.Tag)
End Sub

Do I need to use the two Dispose statements? Is it redundant because their scope is limited to PopulateFilter()? Anything else that I'm missing/should be aware of?

VB
VB
An object-oriented programming language developed by Microsoft that is implemented on the .NET Framework. Previously known as Visual Basic .NET.
2,732 questions
{count} votes

Accepted answer
  1. Peter Fleischer (former MVP) 19,326 Reputation points
    2021-01-09T18:18:33.85+00:00

    Hi James,
    DataSet and DataTable don't actually have any unmanaged resources, so Dispose() doesn't actually do much. The Dispose() methods in DataSet and DataTable exists ONLY because of side effect of inheritance - in other words, it doesn't actually do anything useful in the finalization.

    Dispose is for handling the disposal/release of unmanaged resources or other managed resources that have releasable items, such as SqlConnection.

    The best way is to use USING:

     Private Sub PopulateFilter()
           Using Adapter As New OleDbDataAdapter("SELECT Max(ReceiptDate) AS LastReceiptDate FROM tblReceipts", My.Settings.ReceiptsConnectionString)
             Dim Data As New DataTable
             Adapter.Fill(Data)
             Me.ReceiptsBindingNavigatorYear.Tag = Year(Data(0)("LastReceiptDate"))
          End Using
             Me.ReceiptsBindingNavigatorYear.Text = CStr(Me.ReceiptsBindingNavigatorYear.Tag)
     End Sub
    
    1 person found this answer helpful.

1 additional answer

Sort by: Most helpful
  1. Dewayne Basnett 1,366 Reputation points
    2021-01-11T19:56:48.6+00:00

    This is the best advice IMHO. If an object has a Dispose method it should be called. See link below.

    using-objects

    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.