Resharper Template – Builder Method

Throughout this year, I’ve created countless Builders to support seeding tests across multiple projects. If you don’t know what I’m referring to, check this page on the Builder Pattern.

It quickly becomes a very tedious task, especially for classes with many properties, that made me feel like I should automate this somehow. Through exploring the options to achieve it, I decided to search for a Resharper snippet to generate With methods for every property in a given class.

I wasn’t able to find a way to do that just yet, so I ended up creating a snippet that generates the With method based upon the creation of its back property, the actual snippet implementation comes from SO. Not the ideal solution but it’s a good start, let’s see how it works.

To create a new template/snippet, open Resharper’s Template Explorer by either using the short cut (Ctrl+E, L) or by the menu: Resharper -> Tools -> Template Explorer. On VS2015, it looks like this:

Click on the New Template icon and you’re good to create the template.

The shortcut name of my choosing was bm (builder method). The availability should be Generation, only.

In the actual template, every time you surround something with $, you create a parameter (or placeholder) and its added to the list of parameters on the right. We can add macros to each parameter to smarten the code automation.

  1. For the $type$, I choose to have no macros as it would be impossible to guess the type for every method.
  2. For the $prop$, we tell it to suggest the name and what it’s going to do is name it based on the $type$. This is the same thing that the Resharper’s prop snippet does.
  3. For the $class$, the macro will replace it with the class name, that’s exactly what we need here.
  4. For the $param$, we tell it to use whatever is the content of the prop parameter but start with a lower case character.

And that’s pretty much it. When you save the template, the snippet is already available. All you have to do is type bm, tab and voila:

One of the down sides of this solution is that you may end up with a mix of Property-WithMethod-Property-WithMethod, and this is probably not how you want the layout of the builder to be. To organize it without copying and pasting, hold (Ctrl +Shift+Alt) and use the arrow keys (up/down) to move things around.

I hope this saves you a few keystrokes 🙂

 

 

2 thoughts on “Resharper Template – Builder Method

Leave a Reply

Your email address will not be published. Required fields are marked *