Last Updated: July 27, 2016
· keboo

ReSharper custom patterns

ReSharper is a powerful plugin for Visual Studio that provides a lot of much needed feedback to aid a developer in writing quality code. Though a very poor replacement, it is the closest things to having another developer to pair program with.

In this example I am using ReSharper version 7.0 (at the time of this writing the latest released version).

First lets look at simple program example:

static void Main()
    int value = 1;

    double value2 = 1.0;

    DoSomething(value * 1.0);


public static void DoSomething(int value)
    Console.WriteLine("Do something with int");

public static void DoSomething(double value)
    Console.WriteLine("Do something with double");

The big issue with this program is it multiplies by 1.0 (a double), in order to ensure that a particular override is invoked. This is a clever casting trick that should be avoided. If a type needs to be changed it should be cast to the desired type. This is the issue we will search for and fix using ReSharper custom patterns.

You can think of custom patterns as a really powerful Regex style search that allows for some very intelligent search and replace operations to be performed.

To access the custom patterns, open the ReSharper options window and select Custom Patterns.

We are going to create a new custom pattern that looks like this:

The search pattern is the string in your code that we want ReSharper to find.

Placeholders (variables) within a pattern are declared by surrounding the name with $s. In our case we want to search for things that are being multiplied by 1.0 so the pattern is: $VALUE$ * 1.0

The replacement pattern allows you to also specify a string to replace the code matched by the search pattern. Placeholders that were created in the search pattern can also be used to allow for an intelligent replacement added.

A few other minor things to notice. Setting the severity will have ReSharper underline any matched code with the appropriate color. The description of the search pattern will then be shown in the tooltip when hovering over the code. The description in the replacement pattern will be shown as the Resharper quick fix option.

This looks like this:

And after performing the replacement:

More importantly though, these custom patterns can be used to perform search and replace operation on a much larger scale.

Going back to the Custom Patterns within the ReSharper options allows us to search our entire solution for code matching the pattern and select which instances we want to replace.


This is a very brief example, that only scratches the surface of what this feature is capable of performing.

Source: http://dotnetgeek.tumblr.com/post/33147171076/resharper-custom-patterns

Say Thanks