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!)
The real fun comes when you're back in the code (assuming you haven't replaced it yet)
Put the cursor/caret at the start of the Address address
line 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 we place the cursor in the magical spot and won't underline or draw attention to your eyes.
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!