jhon last
jhon last

Reputation: 119

Do i have to dispose the Bitmap in the method?

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;
            }
        }

Upvotes: 1

Views: 854

Answers (2)

jmcilhinney
jmcilhinney

Reputation: 54417

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.
}

Upvotes: 4

Pete
Pete

Reputation: 65

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.

Upvotes: -2

Related Questions