Visual Studio Field Refactoring Trick

November 15, 2017
No Comments.

I’ve been using a new trick on my courses as of late that I’ve been getting some questions about. I figured I’d just blog about it to share the trick.

The trick in question is taking a constructor parameter and storing it in a class field. Most of it is just refactoring, but there is a way to customize what it looks like.

I like to use factoring to build up my code as I write. I’m not a Resharper guy, but i’ll use it as much as I can. I just don’t like to re-setup Resharper on every install. I’m basically lazy.

If you’ve used refactoring before, then this animation won’t surprise you. You can see here that I’m:

  • Creating a Construtor with the ‘ctor’ snippet
  • Adding the namespace to the IConfiguration type
  • Adding a field to match the incoming constructor parameter

Field Trick

This works ‘out of the box’, but customizing it to be the style I like was harder to figure out. You see, I prefer the _ prefix and camel-casing. You might prefer some other style (and out of the box it’s a little different). To customize what is generated, you need to look in the

C# Naming

You’ll find a lot of the refactoring options in the Code Style part of the Text Editor/C# section. Neat, huh?

What do you think?