Auto format C# code In Visual Studio Code
I have found an option which makes it easier to format code while typing.
I applied the below settings in workspace settings:
{
"editor.formatOnSave": true,
"editor.formatOnType": true
}
This works fine for me.
Go to menu File → Preferences → Keyboard Shortcut (Ctrl + K, Ctrl + S)
Click on the keybindings.json
link:
Enter the below binding for the Enter key. This binding will overwrite the defaults for current user.
{
"key": "enter",
"command": "editor.action.formatDocument",
"when": "editorHasSelection"
}
Another alternative solution is to use macros extension - a custom macros support for Visual Studio Code, so you will be able to do more than one command in one key binding.
Add macros to User Settings
:
"macros": {
"formatWithEnter": [
"editor.action.insertLineAfter",
"editor.action.formatDocument"
]
}
And the below key binding to keybindings.json
:
{
"key": "enter",
"command": "macros.formatWithEnter"
}
Go to menu File → Preference → Settings.
Search for format
Select the options you would like:
Format on Paste
Format on Save
Format on Type
Close the Settings window.
You can also see it in your settings.json file: