Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Namespace indentation in Visual Studio with C#

Visual Studio indents code within namespace. This can be avoided when disabling indentation globally, which is not what I want. In all other cases, the indentation is fine, I simply don't like the fact that all code is one level - this makes it look ugly to me.

namespace X
{
    public class A
    {}
}

I would prefer it like this:

namespace X
{
public class A
{

}
}

In C++, there's a nice workaround as explained here:

namespace X
{; // the ; after opening brace makes visual studio not indent the class below.

class A
{};

}

But in C#, a namespace cannot directly contain fields so this doesn't work.

How can I get Visual Studio to stop indenting namespaces without disabling indentation globally?

Update Visual Studio 2013 behavior C++ has changed

Tools->Options->C/C++->Formatting->Indentation: [ ] Indent namespace contents 

enables my preferred formatting, while the {; trick doesn't work anymore. But no change for C# that I could find.

like image 274
Wilbert Avatar asked May 22 '13 08:05

Wilbert


People also ask

Does C support indentation?

1 The indent Program. The indent program can be used to make code easier to read. It can also convert from one style of writing C to another. indent understands a substantial amount about the syntax of C, but it also attempts to cope with incomplete and misformed syntax.

Should namespaces be indented?

The contents of namespaces should not be indented.

How do you move indentation code in Visual Studio?

You can change the size of indentation by clicking on the Select Indentation setting in the bottom right of VS Code (looks something like "Spaces: 2"), selecting "Indent using Spaces" from the drop-down menu and then selecting by how many spaces you would like to indent.


2 Answers

  1. Text Editor → c# → Tabs → Indenting — Set to "Block"
  2. Text Editor → c# → Formatting → General — Turn off every checkbox saying "automatically format..."
like image 91
cesarito Avatar answered Oct 04 '22 08:10

cesarito


This question deserves a new answer in 2021. C#10 (shipped with .NET 6 and Visual Studio 2022) introduces File Scoped Namespaces. It allows the following syntax:

namespace Hello.World;

class MyClass
{
    public static void Main()
    {
        Console.WriteLine("Hello, World!");
    }
}

So, we can completely remove indentation added by the namespace declaration. The old syntax is supported too.

like image 38
Paweł Bulwan Avatar answered Oct 04 '22 10:10

Paweł Bulwan