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!

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s