There are a lot of questions on SO lamenting the fact that Code Analysis rule CA2000 is being applied possibly too rigorously by VS2010, but I seem to have run into a case where it should be applied, but isn’t.
Consider the following code:
Image srcImage = Image.FromFile(source);
Bitmap newImage = new Bitmap(newWidth, newHeight);
using (Graphics gr = Graphics.FromImage(newImage))
{
gr.DrawImage(srcImage, new Rectangle(0, 0, newWidth, newHeight));
}
newImage.Save(destination, ImageFormat.Jpeg);
Now if I run Code Analysis in Visual Studio 2010 on this, it will complain about newImage not being disposed (easy fix, put it in another using block), but it doesn’t complain about srcImage (which also has a Dispose() method that I’m never calling). Does anyone know why Code Analysis doesn’t complain here?
Well it should “complain about srcImage” too, however I guess that it doesn’t complain about it because you are passing it to the
DrawImagemethod “gr.DrawImage(srcImage, new Rectangle(0, 0, newWidth, newHeight));“, So either it is not smart enough to know that it will not being used for more actions after the method returned, or maybe it assumed that you used it ingrinstance that will be disposed. Anyway you should useusingforsrcImagejust like what you are doing withnewImageand don’t follow the Code Analysis on that.