Search code examples
c#.netwinformscontrolsdispose

WinForms and disposing custom controls


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?


Solution

  • 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).