Repeat custom search template to alert IDisposable objects

Since resharper still does not give any warnings about objects that implement IDisposable, I would like to create some custom search templates available in resharper 5.0.

So far I have this:

(And do not mind that my comments are replaced in templates, I don’t care, I just want to get a clear warning in the code when working with disposable objects.)

- <CustomPatterns> - <Pattern Severity="WARNING"> <Comment>This class implements IDisposable interface.</Comment> <ReplaceComment>Please use Using statement, or dispose the object manually when done using.</ReplaceComment> <SearchPattern>$type$</SearchPattern> <Params /> - <Placeholders> <IdentifierPlaceholder Name="var" Type="" ExactType="False" RegEx="" CaseSensitive="True" /> <TypePlaceholder Name="type" Type="System.IDisposable" ExactType="False" /> <ArgumentPlaceholder Name="args" Minimal="-1" Maximal="-1" /> </Placeholders> </Pattern> - <Pattern Severity="WARNING"> <Comment>This class implements IDisposable interface.</Comment> <ReplaceComment>Please use Using statement, or dispose the object manually when done using.</ReplaceComment> <SearchPattern>new $type$($args$)</SearchPattern> <Params /> - <Placeholders> <IdentifierPlaceholder Name="var" Type="" ExactType="False" RegEx="" CaseSensitive="True" /> <TypePlaceholder Name="type" Type="System.IDisposable" ExactType="False" /> <ArgumentPlaceholder Name="args" Minimal="-1" Maximal="-1" /> </Placeholders> </Pattern> </CustomPatterns> 

This handles variable declaration cases, for example

 Bitmap myBitmap = GetBitmap(); private Bitmap _bitmap; 

and CTOR calls, for example

 var myBitmap = new Bitmap(...); 

What this does not support is:

 var myBitmap = GetBitmap(); 

I cannot find an example of how to define a search pattern that either finds use of "var" or the type of the return method, which is typeof IDisposable.

I am sure there is a way, but I can not find it.

+2
source share
2 answers

The problem with these templates is that they do not disappear when you actually dispose of the object, unless local variable declarations are used inside statements. It also does not track ownership of objects, for example. for factory methods and pass-through methods. Therefore, I believe that doing this through structured templates next to useless ones.

In any case, you may need two templates to check the local variable, for example

 var $identifier$ = $expression$; $type$ $identifier$ = $expression$; 

where expression and type implement IDisposable.

+2
source

Although this does not give a direct answer to your question, there are various runtime methods to find unisolated IDisposable s. Here is one such method .

0
source

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


All Articles