views:

84

answers:

1

Hi, I have a windows form where I set the BackgroundImage property to a custom bitmap image.

private Image MakeCustomBackground()
{
    Bitmap result = new Bitmap(100, 100);

    using(Graphics canvas = Graphics.FromImage(result))
    {
        // draw the custom image
    }

    return result;
}

private void UpdateFromBackground()
{
    this.BackgroundImage = MakeCustomBackground();
}

My question is, Image is disposable and I am creating it, does that mean that I must dispose of it? Or when I pass the image to the form, via BackgroundImage, does it take ownership and dispose of it when it no longer needs it?

+2  A: 

Assuming that UpdateFromBackground() is called more than once, you probably should Dispose the old Image when (before) setting a new one. If you don't then the CG will do it eventually but that is less efficient. The Form will only Dispose the last BgImage you assigned.

private void UpdateFromBackground()
{
    if (this.BackgroundImage != null)
    {
       this.BackgroundImage.Dispose();
    }
    this.BackgroundImage = MakeCustomBackground();
}
Henk Holterman