Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I use a file-scoped namespace declaration in a class template?

C# 10 introduced file-scoped namespaces, which I would like to use in Visual Studio's class templates. I've updated the 'Class' template file to the following:

namespace $rootnamespace$;
class $safeitemrootname$
{
    //I put this comment here to make sure it's using the right file
}

But when I create a new empty class I get this autogenerated code:

namespace ProjectName
{
    internal class Class1
    {
        //I put this comment here to make sure it's using the right file
    }
}

What do I need to do to make the auto-generated code for an empty class look like this?

namespace ProjectName;  
internal class Class1
{

}

For reference, I am using Visual Studio 2022 Professional and my project is using C#10 with .NET 6.

The location of the class template file that I am modifying is: C:\Program Files\Microsoft Visual Studio\2022\Professional\Common7\IDE\ItemTemplates\CSharp\Code\1033\Class\Class.cs

like image 220
Nigel Avatar asked Dec 06 '25 01:12

Nigel


2 Answers

You have to set up your project's editorconfig to prefer File-scoped namespaces.

  1. Right click your project. Select "Add" → "New Item"

  2. Select "editorConfig File (.NET)"

  3. Double click the new editorconfig file. In the "Code Style" tab set "Namespace declarations" to "File scoped"

enter image description here

The code template will now work as expected.

like image 101
Nigel Avatar answered Dec 08 '25 14:12

Nigel


Check this thread: https://stackoverflow.com/a/69889803

They use a .editorconfig file where you can specify the namespace declaration style. When creating a new file in VS 2022 it will use that new style

like image 25
niels013 Avatar answered Dec 08 '25 13:12

niels013