8

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 Files\Microsoft Visual Studio\2022\Professional\Common7\IDE\ItemTemplates\CSharp\Code\1033\Class\Class.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.

4
  • isn't it depends on the setting in the project file? Commented Nov 10, 2022 at 3:37
  • @T.S. Maybe you can give me some more details on it? We have 20 projects so didn't look into project settings. Commented Nov 10, 2022 at 3:45
  • Never mind. I was thinking about <ImplicitUsings>enable</ImplicitUsings> . I've never seen using { namespace{..} } Commented Nov 10, 2022 at 4:43
  • @T.S. Sorry my bad. I am updating my code snippets. Commented Nov 10, 2022 at 4:48

2 Answers 2

17

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Fantastic. That saves my life. Thank you!
I edited .editorconfig to use file scoped in one of my solutions, in this solution when I added a class VS add the semicolon to the namespace, in my other solutions it keep working as always, but since I updated to 17.13 it always add brackets in the namesace, I dont want to change the configuration of VS everytime I open a solution with a different configuration
1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.