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")
{
//handle...
}
}
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;
with
var address = (Address)data;
This time open the Patterns Catalog, Resharper -> Options -> Code Inspection -> Custom Patterns
Click Add Pattern
and enter the following details:
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 Quick Fix (the real fun)
Put the cursor at the start of the line as shown and press the famous Alt-Enter
:
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
Last revised: 21 Feb, 2012 01:38 PM History
No new comments are allowed on this post.
Comments
No comments yet. Be the first!