What's the appropriate way to dispose an ImageList
object?
Suppose I have some class with a private ImageList imageList
member. Now, at some moment I perform the following code:
// Basically, lazy initialization.
if (imageList == null)
{
imageList = new ImageList();
Image[] images = Provider.CreateImages(...);
foreach (var image in images)
{
// Does the 'ImageList' perform implicit copying here
// or does it aggregate a reference?
imageList.Images.Add(image);
// Do I need to do this?
//image.Dispose();
}
}
return imageList;
In the same class I have the Dispose
method implementation, which is performed the following way:
public void Dispose()
{
if (!disposed)
{
// Is this enough?
if (imageList != null)
imageList.Dispose();
disposed = true;
}
}
I'm sure there are some potential issues with this code, so could you please help me to make it correct.
ImageList does not own a reference to the original image. When you add an image ImageList copies it. You are free to dispose the original as you find convenient.
However you should call
imageList.Images.Clear();
in your Dispose().Yes, it makes a copy. Note the CreateBitMap call below. Therefore, to keep your resource use as low as possible, you should uncomment your dispose line.
When ImageList disposes, it disposes its copies of all the images. So again, yes, disposing of it when the form closes as you are is the right thing in addition to uncommenting your other dispose line.