Is an object created using the built-in new statement?

The following snippet is taken from an example implementation of ComboBox::DrawItem on this MSDN page :

 e.Graphics.FillRectangle(new SolidBrush(animalColor), rectangle); 

I doubt this part: new SolidBrush(animalColor)

Since this is not intentionally assigned to Dispose and is not completed in using , I assume this is also an example of a bad shape, as the SolidBrush object will be created and will never be deleted.

I have always worked under the assumption that I should use one of the above removal mechanisms directly or the risk of memory leak.

Is it right, or is there some deeper hidden disposal that I don't know about? Perhaps because it was never bound to a variable?

+7
c #
source share
4 answers

It must be inside the using statement or it must explicitly call Dispose , but ,

SolidBrush class inherits the Brush class, which has a destructor / finalizer defined as:

Source here:

  /** * Object cleanup */ /// <include file='doc\Brush.uex' path='docs/doc[@for="Brush.Finalize"]/*' /> /// <devdoc> /// <para> /// Releases memory allocated for this <see cref='System.Drawing.Brush'/>. /// </para> /// </devdoc> ~Brush() { Dispose(false); } 

As soon as your SolidBrush object goes out of scope, its destructor will eventually be called. At this point, Dispose will be called releasing any uninstalled resources.

See: Destructors (C # Programming Guide)

The destructor implicitly calls Finalize on the base class object.

The only problem with using the destructor / finalizer is that you cannot predict when the object will be permanently deleted.

+4
source share

I have to say a bad example from msdn. You must Dispose it; no objects will be deleted automatically.

This is not necessarily a leak, Brush implements Finalizer , which will Dispose when collecting garbage, but you should not rely on it.

+1
source share

Like all managed objects, it is automatically freed. This is a key aspect for understanding .NET and C #.

However, this may not be done in a timely manner. And since this object uses a system resource, I really do not consider this an example of a good shape.

0
source share

This object must be deleted, yes.

This suggests that this is a valid course of action, so as not to dispose of some light objects, if it would be really inconvenient to do this. Task is a prime example. A SolidColorBrush in WPF is probably pretty lightweight. If you are sure that not too many of them β€œleak”, this code is fine.

Keep in mind that adding a mechanism to delete here (e.g. using ) is cluttering up the code. This is clearly a (small) flaw for this.

0
source share

All Articles