My question is about IDisposable implementation. To my knowledge, when a code or section is complete, the variable or instance is disposed; please correct me if the statement is wrong. The follow is part of my program:
If Con.State = ConnectionState.Closed Then Con.Open()
Cmd = New SqlCeCommand("Select * from BillItem", Con)
Rdr = Cmd.ExecuteReader()
While Rdr.Read = True
Dim x As New Classes.StockRoster
x.BillID = Rdr("BillID")
x.IsSales = Rdr("IsSales")
x.Quantity = Rdr("Quantity")
x.ContactBase = (From t As CommonCodes.ItemBase In ContactsbaseDict Where t.ID = BillContactDict(x.BillID)).First
x.StockEntityBase = StockEntitydict(Rdr("StockID"))
x.BillDate = Rdr("BillDate")
result.AddRange(x)
End While
Con.Close()
End IF
In case of X variable here, would there be any memory improvement if I x (or StockRoster) would use IDisposable interface?
Couldn’t the resources get disposed by default at end of each loop?
IDisposableis about disposing unmanaged resources such as a database connection. It doesn’t have anything to do with the garbage collection.Your
StockRosterclass doesn’t seem to hold unmanaged resources so it doesn’t need to implementIDisposable. Even if it did, it wouldn’t make sense to dispose it in yourforloop, because you add the instance to the result list that you will later use. Disposing it in theforloop would make the instance unusable in the calling code.