I have the following class:
public class NewListBox : ListBox
{
public NewListBox()
{
}
private ImageList _myImageList;
public ImageList ImageList
{
get { return _myImageList; }
set { _myImageList = value; }
}
}
I am interested in whether disposing of this object will trigger the disposal of fields on the object, such as the ImageList, or should i implement (override) the Dispose method and do this work myself?
Based on the code you have posted, you are not using Designer to implement this control. Thus, you will not have a designer-provided
Dispose(bool disposing)
method or aSystem.CompononetModel.IContainer components
member that your extra control may be added to. I am not sure how ListBox handles itsControls
property, but if it lets you register yourImageList
instance there withControls.Add(ImageList)
, that should get you the automaticDispose()
behavior.Your other option is to override
Control.Dispose(bool)
like the following:this article is very helpful, in the Memory Disposal section.
All classes that implement IDisposable (including all Windows Forms controls) have a Dispose method. This method must be called when an object is no longer needed in order to release resources other than memory. There are two ways this happens:
You should add the ImageList to your control's Components collection, then the base-class implementation of Dispose will Dispose everything in that collection, and you won't have to override Dispose yourself.
If you have any members that are IDisposable but are not Components, then you will have to override Dispose in your control and Dispose them yourself.
(I am using the term Component in the strict sense of objects that derive from System.ComponentModel.Component).
Lot of different answers here ..
I strongly advise to read Garbage Collector Basics and Performance Hints In you case you've two option:
Except if you have thousand of big images in your ImageList (or if you create/close the form hundred of times), you'll not notice any difference between the 2 cases