Resharper 5's new pattern matching seems very powerful, though it takes a bit of tinkering to work out how to use it.
For those who aren't familiar with this feature, it allows you to search for specific patterns within your code. Instances of such patterns may optionally be replaced with an alternative. In IntelliJ this was called structural search and replace. It's much more powerful than simple RegEx search/replace.
I'd like to collect a series of patterns that people are using so that I can learn how to use this feature better.
I propose that each answer include:
- a brief introduction of the rationale for the pattern
- an example of what it would match
- an optional example of a replacement
- the XML generated by exporting the pattern so that others can try it out too
Restarting a Stopwatch
.NET 4 introduces the
System.Diagnostics.Stopwatch.Restart()
method which can tidy up your code.Before:
After:
XML:
Remove enclosing braces around a body.
Example:
This code:
will be replaced (by Ctrl+L to remove foreach row and then run this pattern to remove braces) by:
So only body of braces remains after typing around two shortcuts.
The XML:
JetBrains offer a Sample Pattern Catalog for Structural Search and Replace for download containing 17 patterns:
To 'as' cast.
Example:
This code:
will be replaced by:
So now you have the 'as' cast instead of regular cast.
The XML:
http://david.gardiner.net.au/2010/02/resharper-5-structural-search-and.html
Matching a [Flags] enum bit
.NET 4 introduces the
System.Enum.HasFlag
method which can tidy up your code.Before:
After:
XML: