Reputation: 1422
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?
Upvotes: 0
Views: 137
Reputation: 460278
First, you would never enter the If-clause
if the connection is open what could happen f.e. in case of an exception.
Actually the connection is the best example. Always close connections as soon as possible. The easiest way is to use using-statement
which calls Dispose
at the end (even in case of an exception). So it's similar to a Try/Catch/Finally
. Connection.Dispose
will also close it implicitely.
As a rule of thumb: use the using-statement
for anything implementing IDisposable
(like the SqlCeCommand
above).
To answer you actual question:
would there be any memory improvement if I x (or StockRoster) would use IDispose class, couldn't the resources get dispose by default at end of each loop?
What is memory improvement, IDisposable
is an interface, you could call dispose or close even when the class doesn't implement IDisposable
. That's just a hint that it probably uses unmanaged resources and should be disposed as soon as possible.
Upvotes: 1
Reputation: 17875
IDisposable
is about disposing unmanaged resources such as a database connection. It doesn't have anything to do with the garbage collection.
Your StockRoster
class doesn't seem to hold unmanaged resources so it doesn't need to implement IDisposable
. Even if it did, it wouldn't make sense to dispose it in your for
loop, because you add the instance to the result list that you will later use. Disposing it in the for
loop would make the instance unusable in the calling code.
Upvotes: 1