Visual Studio Field Refactoring Trick


Visual Studio 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?


Ready to Learn Vue with ASP.NET Core?

My new Wilder Minds' course is available as an Early Access for only $79. It will be released on a weekly basis. The first module is now available:

Enroll Today


Shawn
Shawn Wildermuth
Author, Teacher, and Coach




My Courses

Wilder Minds Training
Vue.js by Example (Now Available)
Bootstrap 4 by Example
Intro to Font Awesome 5 (Free Course)
Pluralsight
Less: Getting Started (Coupon Available)
Building a Web App with ASP.NET Core, MVC6, EF Core, Bootstrap and Angular (updated for 2.1)
Using Visual Studio Code for ASP.NET Core Projects
Implementing ASP.NET Web API
Web API Design

Application Name WilderBlog Environment Name Production
Application Ver v4.0.30319 Runtime Framework x86
App Path D:\home\site\wwwroot\ Runtime Version .NET Core 4.6.26919.02
Operating System Microsoft Windows 10.0.14393 Runtime Arch X86