Category: Dotnet

Default ctor injected private member names with underscore prefix in Visual Studio 2019

After a bit of experimentation, you might want to change the default member generation when you add an injected member to your C# constructor in Visual Studio 2019.

Here’s what you likely want to use as a private member in your class:

private readonly IHttpContextAccessor _httpContextAccessor;

Here’s what the constructor (ctor) looks like:

public BearerTokenHandler(IHttpContextAccessor httpContextAccessor)
{
_httpContextAccessor = httpContextAccessor ??
throw new ArgumentNullException(nameof(httpContextAccessor));
}

To get that automatically, you’ll need to change the option for it which is deep inside the Visual Studio options menu.

First, navigate to:

Tools->Options->TextEditor->C#->CodeStyle->Naming

Click on the “Manage naming styles” button.

manage1

Fill it out like this:

manage2

Close that and then choose your new specification naming style for “Private or Internal Field”:

manage3

Click “OK” and it should immediately take effect next time you use the “Quick Refactorings” wizard to add a new member.  Try it out!