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

Resharper structural search and replace Part II - Custom Quick Fixes

You are looking at revision 4 of this page, which may be out of date. View the latest version.  

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

alt text

Click Add Pattern and enter the following details:

alt text

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
You are looking at revision 4 of this page, which may be out of date. View the latest version.

Comments

No comments yet. Be the first!

No new comments are allowed on this post.