Resharper structural search and replace Part II - adding your own quick fixes

Resharper structural search and replace Part II - Custom Quick Fixes

In Part I I covered finding usages with Resharper's 'Search with Pattern' feature.

Now lets turn our focus to replacing usages with our own snippets and creating our own custom quick fixes!

Consider this erroneous code sample you might encounter:

private void HandleMessage(object data)
    Address address = data as Address;//should just cast to Address here
    if(address.StreetName == "easy street")

Why erroneous you say? Well if you expect data to only ever be an Address then you should cast to it instead of using the as operator - That way at least you'll get an InvalidCastException instead of a NullPointerException.
sidenote1 there is obviously a time and place for the as operator I'm just giving an example of where a cast is more appropriate

We'll add a pattern that will replace:

Address address = data as Address;


var address = (Address)data;

This time open the Patterns Catalog, Resharper -> Options -> Code Inspection -> Custom Patterns

alt text

Click Add Pattern and enter the following details:

alt text

Search for:

$type$ $var$ = $expr$ as $type$;

Replacing with:

var $var$ = ($type$)$expr$;

Now you can Save the Pattern and press 'Search Now' which will find our usage as detailed above and give you the option to Replace it (with undo naturally!)
With this specific example you'd never want to Find and Replace All as there would be many valid usages of as; instead we would rather this pattern applied on a per-case basis: enter the real fun...

Your pattern as a Quick Fix

Put the cursor at the start of the line as shown and press the famous Alt-Enter:

alt text

You now have your own quick fix! Since we set the pattern to 'Show as hint' it will only show when you place the cursor in the magical spot and won't underline or draw attention away from you. to reiterate: this quick fix is only applicable in the right situation

sidenote2 seems like a lot of trouble to go to for something that can be fixed fairly easily manually?? depends who you've let loose on your code and how many times you have to replace it

Posted by: Wallace Turner
Last revised: 21 Feb, 2012 01:38 PM History


06 Mar, 2012 07:07 PM

Very cool feature, I always have some common refactoring fixes that I am trying to implement in too many steps, but now it is just 1 configuration and 2 clicks later.

No new comments are allowed on this post.