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 FilePreferencesKeyboard Shortcut (Ctrl + K, Ctrl + S)

Click on the keybindings.json link:

Enter image description here

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 FilePreferenceSettings.

Search for format

Select the options you would like:

  • Format on Paste

  • Format on Save

  • Format on Type

Close the Settings window.

Enter image description here

You can also see it in your settings.json file:

Enter image description here