Search code examples
c#visual-studio-codeformattingomnisharpbraces

VS Code C# braces NOT on new lines


Can't find a way to make formatters put braces on the same line. The default formatter seems to completely ignore all the settings related to new lines.

Some people recommended C# FixFormat extension, but now it's deprecated and gone from the marketplace. I also found this extension, but it makes it clear from the very start that it's not gonna help.

Before

public class ClassName {
    public void CallMethod() { 
        this.LongUglyMethod("1234567890", "abcdefghijklmnopqrstuvwxyz", "ABCDEFGHIJKLMNOPQRSTUVWXYZ");
    }
}

After

public class ClassName
{
    public void CallMethod()
    {
        this.LongUglyMethod(
            "1234567890",
            "abcdefghijklmnopqrstuvwxyz",
            "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
        );
    }
}

The default formatter seems to completely ignore the settings at all. I tried to put these everywhere (as it was told here), but it only considers everything not related to new lines.

{
    "MSBuild": {
        "UseLegacySdkResolver": true
    },
    "FormattingOptions": {
        "NewLine": "\n",
        "UseTabs": true,
        "TabSize": 2,
        "IndentationSize": 2,
        "NewLinesForBracesInLambdaExpressionBody": false,
        "NewLinesForBracesInAnonymousMethods": false,
        "NewLinesForBracesInAnonymousTypes": false,
        "NewLinesForBracesInControlBlocks": false,
        "NewLinesForBracesInTypes": false,
        "NewLinesForBracesInMethods": false,
        "NewLinesForBracesInProperties": false,
        "NewLinesForBracesInObjectCollectionArrayInitializers": false,
        "NewLinesForBracesInAccessors": false,
        "NewLineForElse": false,
        "NewLineForCatch": false,
        "NewLineForFinally": false
    }
}

I tried with: Manjaro Linux, VS Code, Microsoft C# extension, Dotnet 6


Solution

  • In your Visual Studio Code, in the C# extension settings, make sure the Omnisharp: Enable Editor Config Support option (omnisharp.enableEditorConfigSupport) is enabled.

    enter image description here


    Then create a file named .editorconfig in your project directory with the following content:

    [*.cs]
    csharp_new_line_before_open_brace = none
    

    If the file already exists, modify or add the csharp_new_line_before_open_brace = none line in the block for [*.cs] files.


    In order to not have linebreaks before else, catch and finally, also add these lines:

    csharp_new_line_before_else = false
    csharp_new_line_before_catch = false
    csharp_new_line_before_finally = false
    

    If you want to apply the settings in all your projects, you can either

    • place the .editorconfig file in a common parent directory of your project directories or
    • place the .editorconfig file in the home directory. In Windows, this is the directory under %HOMEPATH%.