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?
CA2000 and the similar/related CA2213 (DisposableFieldsShouldBeDisposed) and CA1001 (TypesThatOwnDisposableFieldsShouldBeDisposable) rules are rather strict about how they recognize "ownership" of a disposable. They will only consider your code to be the owner of a disposable instance if an instance constructor is used to create the instance directly in your code. Since you use Image.FromFile to create the instance for srcImage, the rule doesn't recognize your code as the owner.
If you disagree with this rule behaviour, you may want to create a bug report at https://connect.microsoft.com/visualstudio/feedback. (If you care about the disposable field rules, you might want to vote for the existing https://connect.microsoft.com/VisualStudio/feedback/details/485291/typesthatowndisposablefieldsshouldbedisposable-rule-ca1001-is-too-permissive suggestion while you're at it.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With