15

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

Nigel
  • 2,961
  • 1
  • 14
  • 32

2 Answers2

21

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.

Uwe Keim
  • 39,551
  • 56
  • 175
  • 291
Nigel
  • 2,961
  • 1
  • 14
  • 32
  • 2
    Not only can you add an ".editorconfig" file to your project, but you can also add it to your solution and have it work for all of your projects in that solution. – Uwe Keim Dec 15 '21 at 15:27
  • @UweKeim in mytesting this is quite limited though – Mr. Boy Oct 12 '22 at 15:13
4

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

niels013
  • 41
  • 1
  • Hey niels, thanks for the answer. I was able to figure it out using that thread. I will write up a more detailed answer that is more up to date for VS2022 – Nigel Nov 17 '21 at 18:27