Check this code:
.. class someclass : IDisposable{ private Bitmap imageObject; public void ImageCrop(int X, int Y, int W, int H) { imageObject = imageObject.Clone(new Rectangle(X, Y, W, H), imageObject.PixelFormat); } public void Dispose() { imageObject.Dispose(); } }
Bitmap is ICloneable , IDisposable in C #.
To avoid memory leaks, for a one-time object, usually use using , then the object will be automatically deleted by the system regardless of how your code went wrong.
In my example, I cannot use using , since I do not want to delete the object, I need it later (the whole class will be located with its IDisposable .
My question is: I have an imageObject , then I use its Clone() method to clone a new object and pass it to the old object variable. This will lead to the fact that the object (either cloned or original) will not go anywhere and will never be deleted, a memory leak.
[EDIT]
It seems that most Clone views call an extra object, the old one should be Dispose()
Here is the new code:
public void ImageCrop(int X, int Y, int W, int H) {
and that should be right Dispose the resources.