skip to Main Content

When using an .editorconfig to configure formatting and enabling automatic formatting (or running dotnet format, is there any way to suppress the formatting for a specific region/block of code?

E.g. I have one file with 1000 constants defined which are aligned in neat columns. For such exceptions I want to use something like

class Example
{
#preserve-format
   // A block I want automatic formatting to just ignore
   const int A      = 123;
   const int Longer = 234;
   const int ...
   ...
#end-preserve-format

   // Formatter works normally here
   public void Foo() 
   { 
   } 
}

Is there anything that will accomplish this?

2

Answers


  1. As an alternative to #pragma you could split the class into two parts and apply a different formatting rule for the file that contains the neatly formatted constants, e.g.:

    Example class Part 1: Example.Part1.cs

    partial class Example
    {
       // A block I want automatic formatting to just ignore
       const int A      = 123;
       const int Longer = 234;
       // ...
    }
    

    Then add the rest of the class into Part 2: Example.Part2.cs

    partial class Example
    {
       // Formatter works normally here
       public void Foo() 
       { 
       }
    }
    

    In your .editorconfig you can then override the formatting rules for the Example.Part1.cs file:

    [*/**Example.Part1.cs]
    csharp_space_around_declaration_statements = ignore
    
    Login or Signup to reply.
  2. Yes, you can use #pragma

    class Example
    {
    #pragma warning disable format
       // A block I want automatic formatting to just ignore
       const int A      = 123;
       const int Longer = 234;
       const int ...
       ...
    #pragma warning restore format
    
       // Formatter works normally here
       public void Foo() 
       { 
       } 
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search