Home Visual Studio - .editorconfig and file-scoped namespaces
Post
Cancel

Visual Studio - .editorconfig and file-scoped namespaces

.NET 6 introduces with C#10 a new way for declaring namespaces called file-scoped namespaces. It means you can now declare a namespace per file with a one-line statement rather than nesting your code block within the namespace scope.

To do so is pretty simple. We want to transform this:

namespace NET6.Features.ConsoleApp
{
	class Program
	{
		static void Main(string[] args)
		{
		}
	}
}

into this:

namespace NET6.Features.ConsoleApp;
class Program
{
	static void Main(string[] args)
	{
	}
}

I found this new style way cleaner by removing an unnecessary indent. Notice that one source file can only contain one file-scoped namespace declaration.


Automatically styling


Working professionally or for personal projects, one thing is for sure: we want our codebase to be consistent, which goes for coding style. There’s the main file you can configure such settings, which is the .editorconfig.

According to Microsoft

EditorConfig settings take precedence over global Visual Studio text editor settings. This means that you can tailor each codebase to use text editor settings that are specific to that project.

So let’s use it to apply this new coding style to an existing project.

Setting the rules

With Visual Studio 2022, you can add one to the root of your solution, and if you open the file with the IDE, you can set it up through a handy UI like this:

The Namespace declarations is what interests me, and you can select the severity from the dropdown list. I set it as a suggestion. At the end (with other settings of mine), my .editorconfig file looks like this:

Quick actions

Heading to the Program.cs file of the project I’ve been using so far for demoing .NET6 features, notice the namespace declared in the old-style:


You can see the small lamp icon on the left side of the namespace declaration, which is the Quick Actions shortcut. It can also be accessed by pressing CTR + . over the line you need. That should display the following actions based on previously defined in the .editorconfig.


As I’ve chosen to Convert to file-scoped namespace at the solution level, I was prompted with the list of files that could be affected since they weren’t complying with the rules I defined. You can select and preview them individually.

Once and for all

There’s a tool called dotnet-format that can help us apply coding style preferences to a project or solution. All that’s needed to apply everything we defined in the config is heading to the sln folder and running:

1
$ dotnet format .\NET6.Features.sln


Check the project on GitHub



This post is licensed under CC BY 4.0 by the author.