Thursday, 25 February 2010

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:

  1. Go to Resharper | Tools | Patterns Catalog
  2. Click on 'Add Pattern'
  3. Enter "$value$ == "" " in the Search Pattern textbox.
  4. Click on 'Add Placeholder' and add an 'Expression' placeholder named 'value' of type System.String
  5. Enter "string.IsNullOrEmpty($value$)" in the Replace Pattern textbox
  6. Ensure Pattern Severity is set to at least 'Show as suggestion'
  7. 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.

 Resharper 5 - Smart Tag showing option to replace with String.IsNullOrEmpty

If you can't wait for the final release of ReSharper 5 (due in the next few months) then install beta 2 or one of the recent nightly builds.


Ben Laan said...
This comment has been removed by the author.
Ben Laan said...

Dave, no doubt you know that this feature is already in CodeRush/Refactor? :-)

Also, while I'm at it, you spelled the description on the smart tag differently to the method Name - I know how much you like things all orderly..

IsNullorEmpty() should be IsNullOrEmpty()

David Gardiner said...

Yes, this is one area where ReSharper is playing 'catchup', and I'd guess it still isn't that close to approaching the templating power that CodeRush has.

Good spot with the messy case :-)


Drew Noakes said...

R# seems to do this out of the box now, meaning you don't need to add it yourself (I'm using build 5.1.1757.11).

One case that it doesn't cover is:

s == null || s.Trim().Length == 0

It would also be nice to have support for the new .NET 4 string.IsNullOrWhitespace method. I requested this a little while ago:

David Gardiner said...

Hey Drew, you know I think I happened to notice the same thing the other day (surprised me as I didn't think I'd put that template into Resharper on the PC I was using)

Maybe they'll include your suggestion in R# 6.0!


Unknown said...

Ben Laan said...
Dave, no doubt you know that this feature is already in CodeRush/Refactor? :-)

Can you point me to some documentation regarding CodeRush/Refactor's implementation of this feature?

From this post I would say CR/R does not in fact have this feature, but instead only have a plugin framework that requires the user to write his own extension to the rule set. This is a far cry from Resharper's Structural Search and Replace: