How to add underscore to your private fields in Visual Studio

I love naming my private fields with an underscore prefix – a convention adopted by many, including Microsoft and used within projects like .NET Core.

Since it’s annoying to hit Ctrl + . and then manually rename the variable both inside the method and out of it every single time, I will show you how you could configure Visual Studio to do that automatically for you.

First, this is the old, slow and overwhelming way:

Let’s say are going to use some service via dependency injection inside your controller, named PeopleController:

    [Route("api/[controller]")]
    public class PeopleController : ControllerBase
    {
        private readonly ICampRepository repository;

        public PeopleController(ICampRepository repository)
        {
            this.repository = repository;
        }

        [HttpGet]
        public object Get()
        {
            return Ok(new { Name = "John Doe", Age = 26});
        }
    }

Now, after Visual Studio automatically added the highlighted code above you must manually rename this.repository to _repository and the readonly field to _repository. And you’ll have to do this every single time. No way.

Here is how you could configure Visual Studio so that this is done automatically for you once you hit Ctrl + .

Inside Visual Studio click Tools and then Options

Visual Studio 2019

Click on Text Editor / C# / Code Style / Naming / Manage naming styles

Visual Studio 2019 Options

Click on the green plus button and fill the fields as follows:

  • Naming Style Title: _fieldName
  • Required Prefix: _
  • Capitalization: camel Case Name
Visual Studio Naming Style

Click OK. The last step is to add all this to the list.

Click on the green plus button and choose the following from the dropdown:

  • First dropdown: Private or Internal Fields
  • Second dropdown: _fieldName
  • Third dropdown: Suggestion
Visual Studio Naming

That’s it! Now every time you want to create a private field Visual Studio would automatically suggest you a variable name with an underscore prefix, like so:

Visual Studio private field with underscore prefix

Hope that was helpful to you.

Happy coding!

Leave a Reply

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