Click here to Skip to main content
15,889,992 members
Please Sign up or sign in to vote.
5.00/5 (1 vote)
See more:
A question I should have probably wondered about a little earlier, but anyway:

Let's say I dim an object, for example a dataset, fill that object with data, and use the object, but do not explicitly clear/empty it after use. Then reuse it like:
MyObject = New Object

Will that automatically clear/empty the data from it, that I filled it with earlier? Or does this depend on the object?

Perhaps the important question here is: what is best practice? Can I get problems by not explicitly clearing/emptying an object before reusing it?

Posted

1 solution

Hi,

assuming VB.NET, if you do
<br />[1]   Dim MyObject As Object<br />[2]   MyObject = New Object  ' object 1<br />[3]   MyObject = New Object  ' object 2<br />


then object 1 will become collectible when line [3] executes, meaning the garbage collector will collect object 1 the next time it runs (normally it runs when a future memory allocation cannot be satisfied without cleaning up memory first).

And this is fine, unless it is a type that implements Dispose or Close, as in:
<br />[1]   Dim MyObject As Font<br />[2]   MyObject = New Font(...) ' object 1<br />[4]   MyObject = New Font(...) ' object 2<br />


now you should insert [3] MyObject.Dispose() to make sure the unmanaged resources that might be held by the object get released right away (or the file or stream or whatever gets closed).

If you don't Close/Dispose objects that support it, your app will use more memory and other system resources, and its behavior may deteriorate. Yes, the garbage collector will still find those objects, and its finalizer thread will eventually Dispose of them, but that typically will be much later.

:)

 
Share this answer
 


CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900