Question Is disposing a local brush variable necessary?

priyamtheone

Well-known member
Joined
Sep 20, 2007
Messages
96
Programming Experience
Beginner
MSDN recommends disposing any variable of type System.Drawing.Brush before its last reference is released. Otherwise, the resources it is using will not be freed until the garbage collector calls the Brush object's Finalize method.

As we know, local variables are destroyed automatically when the control flow goes out of the scope of the method it belongs. So, is it necessary to dispose a brush object every time if it is local?
 
Yes, it is always necessary to dispose objects before you 'release' them. That the variable goes out of scope just means that the memory allocated to that variable is freed, the object it referred to (and its memory) lives on, and it can take a long time before GC is finalizing objects.
Also read the remarks for Brushes class.
 
Disposing an object is not even about memory. If you dispose a Brush and then the variable that referred to it goes out of scope then, as JohnH says, the stack memory allocated to the variable is freed but the memory occupied by the Brush object is still allocated. Disposing doesn't change that. What disposing does is release resources other than memory, which basically means system handles. That's why you can still do things with disposed objects but you can use them usefully, e.g. you can dispose a form and still access many of its property values, but you can't show it. If you don't dispose objects then it's possible that the system may still have plenty of memory left but it runs out of other resources.
 

Latest posts

Back
Top