Resharper code pattern for IDisposable is not used internally

I would like to know how to create a Resharper (6.1) code template to find and replace the following problems:

var cmd = new SqlCommand();


and turn it into this:

using (var cmd = new SqlCommand())



 StreamReader reader = new StreamReader("myfile.txt");
 string line = reader.Read();



using (StreamReader reader = new StreamReader("file.txt"))
   string line = reader.ReadLine();


EDIT: Thanks for the answers, but I'm looking for anything that implementsIDisposable


source to share

3 answers

Search scheme:

var $cmd$ = $sqlcommand$;


Replace Template:

using (var $cmd$ = $sqlcommand$)


where cmd

= id

and sqlcommand

= type expressionSystem.Data.SqlClient.SqlCommand



It looks like what you are actually after is a validation mechanism that disappears looking for objects IDisposable

and makes sure they are removed. If so, I doubt custom templates would be the right approach - after all, what if you call a Dispose()

few lines later?

One way to do this is using the ReSharper SDK . In fact, one example that the SDK comes with is PowerToy, which implements IDisposable

for a specific class, so you can take that code as a basis for a possible usage analysis.



Use the Search with Pattern tool in ReSharper | Find the menu.

In your search template, make sure you select C # and enter the code you are looking for in the box. Click the Replace button in the upper right corner and enter the code you want to replace in the Replace Template field.

You can save the search and replace pattern, and R # will use it to analyze the code later if you wish. You can also add additional templates to the R # options under Code Review | Custom templates.



All Articles