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();
cmd.ExecuteNonQuery();
and turn it into this:
using (var cmd = new SqlCommand())
{
cmd.ExecuteNotQuery();
}
and
StreamReader reader = new StreamReader("myfile.txt");
string line = reader.Read();
Console.WriteLine(line);
becomes:
using (StreamReader reader = new StreamReader("file.txt"))
{
string line = reader.ReadLine();
Console.WriteLine(line);
}
EDIT: Thanks for the answers, but I'm looking for anything that implementsIDisposable
source to share
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.
source to share
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.
source to share