skip to Main Content

I want VS to generate new classes using the new way of declaring namespaces, ie:

namespace A.Namespace.For.Class;
public class ANewClass
{
}

But my VS2022 still uses the old way, ie:

namespace A.Namespace.For.Class
{
    public class ANewClass
    {
    }
}

So I tried to change the template file located at
C:Program FilesMicrosoft Visual Studio2022ProfessionalCommon7IDEItemTemplatesCSharpCode1033ClassClass.cs

I changed it to the below:

namespace $rootnamespace$;
public class $safeitemrootname$
{
}

But it looks like VS2022 can’t interpret the semicolon after the namespace’s name because it still uses the old style. But as soon as I remove the semicolon, VS starts to use the new style except that I now have to manually add that semicolon myself.

Anyone knows how to escape that semicolon in that code template file? No documentation seems to be available.

2

Answers


  1. You don’t have to change the template, this is configurable, go to

    Options > Text Editor > C# > Code Style > General

    In Code block preferences section, change Namespace declarations to File scoped.

    Login or Signup to reply.
  2. The answer of @shingo is the best, I think, but it is worth mentioning, that you can achieve the same by modifying the template (as you did) plus disable the auto formatting (back to block-scoped namespace) in the .editorconfig file. (Source: https://blog.jdriven.com/2022/12/changing_visual_studio_cs_templates/)

    [*.cs]
    csharp_style_namespace_declarations=file_scoped:suggestion
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search