Search code examples
c#.netvisual-studioeditorconfig

Avoid Visual Studio autoformatting code in specific region


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?


Solution

  • 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() 
       { 
       } 
    }