6

I want to use a Resharper structural search and replace template to automatically replace examples of this:

new Fruit { Name = "Apple", IsTasty = true }

With this:

new Fruit("Apple", true)

(Note, the required constructor already exists)

I've tried various combinations like this:

new $type$ { Name = $name$, IsTasty = $isTasty$ };

...using various different Placeholder types, but R# doesn't find any of the examples in my code. Has anyone done this before?

Yuval Itzchakov
  • 146,575
  • 32
  • 257
  • 321
Chris Brook
  • 2,335
  • 20
  • 24

2 Answers2

6

So I just did this in resharper (9.0.2 I think)

Create pattern: FruityChange

  • new $type$ { Name = $param1$, IsTasty = $param2$ }
  • $type$ is a type
  • $param1$ is an expression of type string
  • $param2$ is an expression of type bool
  • Pattern Severity "Show as error"

with class Fruit

public class Fruit
{
    public Fruit(string name, bool isTasty)
    {
        Name = name;
        IsTasty = isTasty;
    }

    public string Name { get; set; }
    public bool IsTasty { get; set; }
}

And that underlined the expression in the code editor and alt-tab gave me the "Replace With" option for it. It at least works on my machine :-)

pms1969
  • 3,354
  • 1
  • 25
  • 34
  • 1
    This worked - thanks! I think the issue was that I had included the terminating semi-colon at the end of the statement. You must leave this off. – Chris Brook Apr 17 '15 at 09:59
2

By default, it seems R# treats your placeholders as identifiers, and the pattern match fails.

Double-click each placeholder on the right side, and change "identifier" to "expression".

enter image description here

Grant Winney
  • 65,241
  • 13
  • 115
  • 165