Home > Software design >  Do i have to dispose the Bitmap in the method?
Do i have to dispose the Bitmap in the method?

Time:10-05

The method return the Bitmap variable nb, do i need to dispose this variable somewhere in the method and if i do where to do it ?

public Bitmap cropAtRect(Bitmap b, Rectangle r)
        {
            Bitmap nb = new Bitmap(r.Width, r.Height);
            using (Graphics g = Graphics.FromImage(nb))
            {
                g.DrawImage(b, -r.X, -r.Y);
                return nb;
            }
        }

CodePudding user response:

The point of disposing is to release resources held by an object. Disposing is something you do when you're finished with an object. If your method is returning that Bitmap then it obviously expects that Bitmap to be used after the method completes, so disposing it in the method wouldn't make any sense. What would probably make sense is the code that calls your method would use the Bitmap it returns and then dispose it, e.g.

Bitmap bmp;
Rectangle rect;

// ...

using (var newBmp = cropAtRect(bmp, rect))
{
    // Use newBmp here.
}

CodePudding user response:

c# should take care of that for you some time after the last reference to the bitmap goes out of scope. If you are worried about it you can watch your memory use while debugging or write a test case that creates many bitmaps with your function.

  • Related