Using Resharper to Identify IDisposable Instances

Can Resharper (v 7.1.3) help identify code that does not use the "using" keyword when creating objects that implement IDisposable (ie SqlConnection, StreamReader)?

+4
source share
1 answer

Only ReSharper cannot do this.

FXCop cannot do this either, unfortunately. FXCop can warn of types that contain fields of types that implement IDisposable, but a type that contains them does not implement IDisposable. This is not what is being asked for here.

What you need is Visual Studio 2012, and then enable the code analysis engine to work with your code. Be sure to include the rule set that contains the rule.

enable code analysis

In particular, you want to enable the CA2000 warning:

CA2000

after including this and writing the code as follows:

namespace ConsoleApplication1 { class Program { static void Main(string[] args) { var stream = new MemoryStream(); } } } 

You will get the following:

d: \ Dev \ VS.NET \ ConsoleApplication1 \ ConsoleApplication1 \ Program.cs (14): warning: CA2000: Microsoft.Reliability: in the method 'Program.Main (string [])', call System.IDisposable.Dispose on the object " stream "before all links to it go beyond.

Note In some cases, this will create both false negatives and false positives. First, the rule detects and does not warn that you are returning such an object.

However, in the method in which you return the object, it will only call the fact that you do not dispose of it in some cases.

In particular, this will generate a warning:

 static void Main(string[] args) { var stream = CreateStream(); // warning here } private static MemoryStream CreateStream() { return new MemoryStream(); } 

whereas it will not:

 static void Main(string[] args) { var stream = GetStream(); // NO warning here } private static MemoryStream GetStream() { return new MemoryStream(); } 

The rule seems to detect that Create is a prefix for the factory method, so it hits the caller to delete the object, whereas Get is not such a prefix, so it gets to the method called to delete it, but since it returns the object, it also does not bear this responsibility.

+14
source

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


All Articles