ReSharper 5 – Structural Search and Replace
I found a use today for a new feature that will be in ReSharper 5.0 - “Structural Search and Replace”. Essentially it’s a way to add code matching templates into R# to add new refactoring patterns in addition to those that come in the box.
For example, Microsoft recommends (and Code Analysis/FxCop generates appropriate warnings) if you are doing a comparison between a string value and an empty string, to use the String.IsNullOrEmpty() method.
I always wanted R# to make this change for me, and now I can:
Go to Resharper Tools Patterns Catalog
- Click on ‘Add Pattern’
- Enter “
$value$ == ""“ in the Search Pattern textbox.
- Click on ‘Add Placeholder’ and add an ‘Expression’ placeholder named ‘value’ of type System.String
- Enter “
string.IsNullOrEmpty($value$)” in the Replace Pattern textbox
- Ensure Pattern Severity is set to at least ‘Show as suggestion’
- Click on ‘Add’
R# will now use this pattern and highlight code that matches. You can then hit the QuickFix shortcut (Alt-Enter by default) and get a smart tag offering to refactor/replace your code.