Search code examples
c#c#-4.0disposeunmanagedsystem.drawing

System.Drawing objects unmanaged resource disposing


I have the following code:

using System.Drawing;
...
Graphics _graphics = Graphics.FromImage(...)
...
public void Draw(Stream stream, Rectangle rect, Color color) {
    _graphics.FillRectangle(new SolidBrush(Color), 0, 0, Width, Height);
    _graphics.DrawImage(new Bitmap(stream), rect);
}

Should I surround the drawImage with using on new Bitmap(...)? Same question on the new SolidBrush(...)


Solution

  • Yes, you should wrap them in using statements. Also you should ensure that the Dispose methods is invoked on the _graphics instance that you are using in this class. This could be done by having the containing class implement IDisposable so that the consumer of this class could wrap it in a using statement.