tisdag 13 november 2018

Alter template for "Create and initialize field" in Visual Studio to get fields prefixed with underscore

I've got a fresh installation of Visual Studio and this time I haven't added Resharper. And so far I don't miss it! I haven't been hammering out that much code, but it seems like the built in code assistent in Visual Studio has become way better, because I usually, almost immediately, greatly miss the extra help I get from Resharper.

What I've already found though, is that its auto generation of fields from parameters to the constructor needs some tweaking. Well, if you like to prefix your fields with an underscore that is.

In case you didn't know, you can position the marker on a new constructor parameter and press "Ctrl + ." to open up the Quick Actions and Refactorings menu.
Then you can choose to Create and initialize field and get presented with a preview of what the result will look like.
The images below shows what it looks like with the default setting.




Visual Studio automatically creates the field "arg1" and assigns it with the constructor parameter.


I prefer fields to be prefixed with underscore to make it possible to immediately distinguish fields from local variables when reading the code, which I think is a great help when trying to get a grip of what the code does. And it seems to be the standard for .net core.


To change the template for this, go to 
Tools -> Options -> Text Editor -> C# -> Code Style -> Naming



Click Manage naming styles. Add a naming style like the one below.



Add a new row by clicking the plus. 
Select Private or Internal Field as Specification.
Select your new naming style as the Required Style.



Click OK. 
I had to restart Visual Studio make the update work.

Now it looks like this:


And the result is:




Of course Stack Overflow had the remedy when I became tired of renaming my auto generated fields and removing "this.". So thanks for that kspearrin and Maciek! :)

Inga kommentarer:

Skicka en kommentar