Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does Bitmap cause rule CA2000, but Image does not?

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?

like image 974
Alex K Avatar asked Aug 07 '11 15:08

Alex K


1 Answers

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

like image 116
Nicole Calinoiu Avatar answered Nov 11 '22 04:11

Nicole Calinoiu