Code Formatting In Visual Studio



Code

-->

Editor behaviors can be set to allow code to be formatted as it is written. These actions are set under Visual Studio Preferences Text Editor Behavior, and some of the more commonly used functions are described below: Matching closing braces can be added automatically to code when creating new classes, methods, or properties. Default Formatter Code formatting is supported using either one of yapf or autopep8. The default code format provider is autopep8. Option 1 Go to any.cs file and open in code editor. Right click on the code file and you will get option to 'Format Code' as shown below. You can also invoke this command using Keyboard shortcut 'Ctrl+D, Ctrl+F'.

Use the Formatting options page and its subpages (Indentation, New Lines, Spacing, and Wrapping) to set options for formatting code in the code editor.

To access this options page, choose Tools > Options from the menu bar. In the Options dialog box, choose Text Editor > C# > Code Style > Formatting.

Code Formatting In Visual Studio

Tip

The Indentation, New Lines, Spacing, and Wrapping subpages each display a preview window at the bottom that shows the effect of each option. To use the preview window, select a formatting option. The preview window shows an example of the selected option. When you change a setting by selecting a radio button or check box, the preview window updates to show the effect of the new setting.

Formatting (General) page

General settings

These settings affect when the code editor applies formatting options to code.

LabelDescription
Automatically format when typingWhen deselected, the format statement on ; and format block on } options are disabled.
Automatically format statement on ;When selected, formats statements at completion according to the formatting options selected for the editor.
Automatically format block on }When selected, formats code blocks according to the formatting options selected for the editor as soon as you complete the code block.
Automatically format on returnWhen selected, formats text when Enter is pressed, to fit the formatting options selected for the editor.
Automatically format on pasteWhen selected, formats text that is pasted into the editor to fit the formatting options selected for the editor.

If you previously applied code style settings for C# files using the Format Document command in Visual Studio 2017, that functionality is now available as Code Cleanup.

Format Document settings

These settings configure the Format Document command to perform additional code cleanup on a file. For more information about how these settings are applied, see Format Document command.

LabelDescriptionCorresponding EditorConfig and Tools > Options rules
Apply all C# formatting rules (indentation, wrapping, spacing)The Format Document command always fixes formatting issues. This setting can't be changed.Core EditorConfig options
.NET EditorConfig formatting options
Tools > Options > Text Editor > C# > Formatting > [Indentation or New Lines or Spacing or Wrapping]
Perform addition code cleanup during formattingWhen selected, applies fixes for the rules specified below on the Edit.FormatDocument command.N/A
Remove unnecessary usingsWhen selected, removes unnecessary using directives when Edit.FormatDocument is triggered.N/A
Sort usingsWhen selected, sorts using directives when Edit.FormatDocument is triggered.dotnet_sort_system_directives_first
Tools > Options > Text Editor > C# > Advanced > Place 'System' directives first when sorting usings
Add/remove braces for single-line control statementsWhen selected, adds or removes braces from single-line control statements when Edit.FormatDocument is triggered.csharp_prefer_braces
Tools > Options > Text Editor > C# > Code Style > Code block preferences > Prefer braces
Add accessibility modifiersWhen selected, adds missing accessibility modifiers when Edit.FormatDocument is triggered.dotnet_style_require_accessibility_modifiers
Sort accessibility modifiersWhen selected, sorts accessibility modifiers when Edit.FormatDocument is triggered.csharp_preferred_modifier_order
visual_basic_preferred_modifier_order
Apply expression/block body preferencesWhen selected, converts expression-bodied members to block bodies, or vice versa, when Edit.FormatDocument is triggered.Expression-bodied member EditorConfig options
Tools > Options > Text Editor > C# > Code Style > Expression preferences > Use expression body for methods, constructors, etc.
Apply implicit/explicit type preferencesWhen selected, converts var to the explicit type, or vice versa, when Edit.FormatDocument is triggered.Explicit type EditorConfig options
Tools > Options > Text Editor > C# > Code Style > 'var' preferences
Apply inline 'out' variables preferencesWhen selected, inlines out variables where possible when Edit.FormatDocument is triggered.csharp_style_inlined_variable_declaration
Tools > Options > Text Editor > C# > Code Style > Variable preferences > Prefer inlined variable declaration
Apply language/framework type preferencesWhen selected, converts language types to framework types, or vice versa, when Edit.FormatDocument is triggered.dotnet_style_predefined_type_for_locals_parameters_members
dotnet_style_predefined_type_for_member_access
Tools > Options > Text Editor > C# > Code Style > predefined type preferences
Apply object/collection initialization preferencesWhen selected, uses object and collection initializers where possible when Edit.FormatDocument is triggered.dotnet_style_object_initializer
dotnet_style_collection_initializer
Tools > Options > Text Editor > C# > Code Style > Expression preferences > Prefer object initializer or Prefer collection initializer
Apply 'this.' qualification preferencesWhen selected, applies this. preferences when Edit.FormatDocument is triggered.this. qualification EditorConfig options
Tools > Options > Text Editor > C# > Code Style > 'this.' preferences
Make private fields readonly when possibleWhen selected, makes private fields readonly where possible when Edit.FormatDocument is triggered.dotnet_style_readonly_field
Tools > Options > Text Editor > C# > Code Style > Field preferences > Prefer readonly
Remove unnecessary castsWhen selected, removes unnecessary casts where possible when Edit.FormatDocument is triggered.N/A
Remove unused variablesWhen selected, removes variables that are unused when Edit.FormatDocument is triggered.N/A

Indentation page

The indentation options on this page apply when code is formatted automatically. One example of when code is automatically formatted is when you paste code into the file while Automatically format on paste is selected. (The Automatically format on paste option is under Formatting > General.)

Tip

2019

Visual Studio Html Editor

There are also indentation options on the Text Editor > C# > Tabs options page. Those options only determine where the code editor places the cursor when you press Enter at the end of a line.

See also

Tutorial

While this tutorial has content that we believe is of great benefit to our community, we have not yet tested or edited it to ensure you have an error-free learning experience. It's on our list, and we're working on it! You can help us out by using the 'report an issue' button at the bottom of the tutorial.

Introduction

Visual

Formatting code consistently is a pain, especially when working on a team. The beauty of modern day web development is that the tooling has gotten so much better! In this article, we will look at setting up Prettier to automatically format your code in Visual Studio Code.

Sample Code

For demo purposes, here’s the sample code we will be formatting. If you’re picky about code formatting, you’ll pick up on some obvious misteps immediately.

  • mix of single vs double quotes
  • the first property of the person object should be on it’s own line
  • the console statement inside of the function should be indented
  • you may or may not like the optional parenthesis surrounding the parameter of the arrow function

Installing the Prettier Extension

To work with Prettier in Visual Studio Code, you’ll need to install the extension. Search for Prettier - Code Formatter. You can see the extension below. If you’re installing it for the first time, you’ll see an “install” button instead of the “uninstall” button you see on mine.

The Format Document Command

With the Prettier extension installed, we can now leverage it to format our code. We’ll work more on this later, but to start, we can use the Format Document command.

To open the command pallette, you can use Command + Shift + P on Mac or Control + Shift + P on Windows. In the command pallette search format, then choose Format Document.

You may then be prompted by to choose which formatter to use. To do so, click the Configure button.

Then choose Prettier - Code Formatter.

And then VOILA! Your code is nice and formatted. Notice all the fancy improvements!

  • spacing
  • line wrappings
  • consistent quotes

Prettier also works with CSS files!

The awesome thing is that this also works on CSS files!

From this…

To this!

Automatically Format on Save

So far, we have had to manually run a command to format our code. Instead, you can choose a setting in VS Code to have your files automatically formatted when you save. This has some great benefits.

You never have to manually format your code again!

  • ensure code is formatted without having to think about it
  • code doesn’t get checked in that’s not formatted

To change this setting, use Command + , on Mac or Control + , on Windows to open the settings menu. Then search for Editor: Format on Save and make sure it is checked.

With this setting in place, you can go about your business writing sloppily formatted code like we all do knowing that it will all be taken care of automatically for you!

Formatting code in visual studio

Prettier Configuration in VS Code Settings

Prettier does a lot of things for you by default, but you can also customize the settings. Here are a few of the most common settings.

  • Single Quote - choose between single and double quotes
  • Semi - choose whether or not to include semi colons at the end of lines
  • Tab Width - how many spaces you want a tab to consist of

Open the settings menu as above. Then, search for Prettier. This will bring up all of the settings that you can change right there in your editor.

For example, what if I change the tab width to 10.

Then save my file.

Pretty easy right?! This is probably not the tab width size you want to keep, but it’s all up to you!

Creating a Prettier Configuration File

The downside to using the built-in settings menu in VS Code is that it doesn’t ensure consistency across developers on your team. If you change settings in your VS Code, someone else could have an entirely different set of settings in theirs.

Establish consistent formatting across your team by creating a configuration file!

To solve this, you can create a Prettier configuration file. It has to be titled .prettierrc.(ext) with one of the following extensions.

  • yml, yaml, or json
  • js
  • toml
  • include in package.json file (alternate option)

I typically prefer JSON configuration files where you can define key -> value pairs for your settings. VS Code will even provide some intellisense for you as you type.

Code Formatting In Visual Studio Shortcut

Here’s an example of a simple configuration file.

For more specifics on the configuration files, check out the Prettier Docs. After creating one of these and checking it in to your project, you can ensure that every team member follows the same formatting rules.

Conclusion

Code Formatting In Visual Studio Code

Don’t waste your time manually formatting your code. It takes time that can be better spent writing more code. Take advantage of the amazing modern tools out there and set up Prettier!