In many occasions I doubt if I need to dispose bitmaps objects. One scenario in which I doubt if it is necessary is the following when from within a method I have to return the bitmap:
private Bitmap SampleMethod(Bitmap bmpOriginal)
{
BitmapData bmdo = null;
Bitmap bm = null;
BitmapData bmdn = null;
try
{
bmdo = bmpOriginal.LockBits(new Rectangle(0, 0, bmpOriginal.Width, bmpOriginal.Height), ImageLockMode.ReadOnly, bmpOriginal.PixelFormat);
bm = new Bitmap(bmpOriginal.Width, bmpOriginal.Height, PixelFormat.Format1bppIndexed);
bmdn = bm.LockBits(new Rectangle(0, 0, bm.Width, bm.Height), ImageLockMode.ReadWrite, PixelFormat.Format1bppIndexed);
// Do some things with bmdo and bmdn objects
bm.UnlockBits(bmdn);
bmpOriginal.UnlockBits(bmdo);
}
catch (Exception e)
{
if (bm != null) bm.Dispose();
}
return bm;
}
What bmp objects do I need to dispose here, bmp? It's not clear for me. Also I have read articles where people do not recommend to dispose bitmaps that are being returned (that is the case).
If you dispose object it internal resources will be destroyed and object will be unusable. So if you return such object, you return unusable object.
Never dispose returned object, never mind what type.
And in
catchSet
nullforbmnot to return a damaged object.