Srikrishna Sharma
Srikrishna Sharma

Reputation: 171

Applying the Code Styling In Visual Studio 2022

I need to setup a common code styling pattern which team needs to follow and will give warning or error to the developer while writing/compiling the code or pushing the code on the repository.

I have gone through couple of sites explaining about the EditorConfig file for setting up the styling in Visual Studio.

Also Gone through the link Code Style Option to give the style to the code.

The problem is Code Style Option have predefined styling.

I need to setup some custom styling in code like

  1. A space before and after = operator
  2. A space after comma in function parameter.
  3. A proper indentation will be applied automatically to that file after the build. etc

If the answer lies in the Editorconfig for this Please let me know a guide to data setup in that file

Upvotes: 2

Views: 3099

Answers (1)

Timothy G.
Timothy G.

Reputation: 9055

Most of what you asked for is, for the most part, already enabled by default, but you can configure it using an .editorconfig as you mentioned. You won't be able to make it as specific as you requested, however by the sounds of it, I would think you'd want this formatting applied for all cases, and not these specific cases you mention. If that isn't the case, then I don't think there any native way to specify the specific formatting you asked for.

Add an .editorconfig file to your project, and open it. Note that you should be able to create .editorconfigs for each project to specify formatting in each, or you can make a global one.

For adding a space before and after an equal sign, the control for this is "Set spacing for operators". This will apply however to all operators. I don't think you can narrow it down to only equal signs:

spacing for binary operators

For spaces after parameters, the control for this is "Insert space after comma". Again, this will be for all commas used throughout your code, not just for parameters:

comma spacing

Lastly, you can control the indentation settings you wish by looking under the Whitespace → Indentation and spacing section:

Indentation

For formatting on build you have some options. You can download a format on save extension, but that wouldn't format on "a build" technically. However I think because when a build is performed, a save of all files automatically occurs, and this should also format them.

One other way I've found is using the dotnet format command as a Post-Build event.

dotnet format post build event

Upvotes: 2

Related Questions