Reputation: 20050
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?
Upvotes: 6
Views: 10550
Reputation: 8308
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 a System.CompononetModel.IContainer components
member that your extra control may be added to. I am not sure how ListBox handles its Controls
property, but if it lets you register your ImageList
instance there with Controls.Add(ImageList)
, that should get you the automatic Dispose()
behavior.
Your other option is to override Control.Dispose(bool)
like the following:
protected override void Dispose(bool disposing)
{
// Only call Dispose() on members if invoked through a direct
// call to `Dispose()`. (If disposing is false, that means
// we are invoked through the finalizer and we should *only*
// free up unmanaged resources that we *directly* own).
if (disposing)
{
ImageList.Dispose();
}
base.Dispose(disposing);
}
Upvotes: 1
Reputation: 2126
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
Upvotes: 2
Reputation: 1714
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:
Upvotes: 6
Reputation: 5452
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).
Upvotes: 6