Why does Bitmap invoke the CA2000 rule, but the image does not work?

There are many questions that SO is mourned by the fact that the CA2000 code analysis rule is applied too strictly VS2010, but I seem to have come across a situation where it should be applied, but it is not.

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, it will complain about newImage , which will not be deleted (easy to fix, put it in another block), but it does not complain about srcImage (which also has the Dispose () method, which I never I do not call). Does anyone know why Code Analysis is not complaining here?

+6
source share
2 answers

Well, he should also "complain about srcImage", but I think he doesn't complain about it because you pass it to the DrawImage method " gr.DrawImage(srcImage, new Rectangle(0, 0, newWidth, newHeight)); " . Therefore, either it is not smart enough to know that it will not be used for additional actions after the method returns or, perhaps, it is assumed that you used it in the gr instance that will be deleted. In any case, you should use using for srcImage in the same way as what you do with newImage , and do not follow the code analysis.

0
source

The CA2000 and similar / related CA2213 (DisposableFieldsShouldBeDisposed) and CA1001 (TypesThatOwnDisposableFieldsShouldBeDisposable) rules are pretty strict on how they recognize β€œone-time” ownership. They will only consider your code as the owner of a one-time instance if the instance constructor is used to instantiate directly in your code. Since you are using Image.FromFile to create an instance for srcImage, the rule does not recognize your code as the owner.

If you do not agree with the behavior of this rule, you can create an error report at https://connect.microsoft.com/visualstudio/feedback . (If you are worried about disposable field rules, you can vote for the existing offer https://connect.microsoft.com/VisualStudio/feedback/details/485291/typesthatowndisposablefieldsshouldbedisposable-rule-ca1001-is-too-permissive while you are on it. )

+5
source

Source: https://habr.com/ru/post/894489/


All Articles