views:

51

answers:

2

Since resharper still doesn't give out any warning regarding objects implementing IDisposable, I'd like to create some custom search patterns available in resharper 5.0.

So far I have this:

(And don't mind my replace comments in the patterns, I don't really care about it, I just want a clear warning in the code when dealing 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 cases of variable declaration, e.g.

Bitmap myBitmap = GetBitmap();
private Bitmap _bitmap;

and CTOR calls, e.g.

var myBitmap = new Bitmap(...);

What it doesn't support, is this:

var myBitmap = GetBitmap();

I can't find any example of how to define a search pattern that will either find 'var' usage, or a method return type, that is typeof IDisposable.

I'm sure there's a way, I can't find it though.

+1  A: 

The problem with these patterns is that they don't go away when you actually dispose the object, except may be for local variable declarations inside using statements. It also doesn't track object ownership, e.g. for factory methods and pass-through methods. So I believe making it through structured patterns is next to useless.

Anyway, you may need two patterns for local variable checks like

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

where expression and type are implementing IDisposable.

Ilya Ryzhenkov
Of course, I understand that, but all I want is a warning when a disposable object is being first declared. Thank you for the queries, but they don't seem to work. If I use only $expression$, it works, but warns every time the object is being used, where I want a warning only in declaration.
Rita
A: 

While this doesn't directly answer your question, there are various runtime techniques to find undisposed IDisposables. Here's one such technique.

Steve Dunn