How to generate class with file-scoped namespace syntax (C# 10) in vs code?

Viewed 854

I would like to generate a new C# Class or C# Interface in Microsoft Visual Studio Code following the newest C#10 file-scoped namespace syntax.

https://docs.microsoft.com/en-us/dotnet/csharp/fundamentals/types/namespaces

Beginning with C# 10, you can declare a namespace for all types defined in that file, as shown in the following example:

namespace SampleNamespace;

class AnotherSampleClass
{
    public void AnotherSampleMethod()
    {
        System.Console.WriteLine(
            "SampleMethod inside SampleNamespace");
    }
}

I'm generating C# classes this way:

Right click on folder in the explorer -> New C# Class.

The output looks like this: (the old syntax with curly braces)

namespace SampleNamespace
{
    class SampleClass
    {
        public void SampleMethod()
        {
            System.Console.WriteLine(
                "SampleMethod inside SampleNamespace");
        }
    }
}

I'm using C# for Visual Studio Code (powered by OmniSharp). v1.24.0

VS Code version is 1.62.3

Is there any way to override the generator behaviour to generate new file-scoped namespace syntax?

2 Answers

Sorry this is a late response but I've just been at this myself.

What you're looking for is a Visual Studio setting.

Go to: Tools > Options > Text Editor > C# > Code Style

The 4th block down, "Code block preferences"

Change "Namespace declarations" from "Block scoped" to "File scoped"

(This is in Visual Studio 2022)

If you don't get the answer you seek in terms of changing the generator, you could consider:

  • Install AutoHotKey
  • Add this to the AHK script:
; CtrlAltN - convert to file scoped namespace
^!N::
KeyWait Control
KeyWait Alt
Send ^{Home}{Down}{Delete}{Delete}^{End}{Backspace}^a+{Tab}
return
  • Make a new class
  • Put the cursor anywhere in it and press Ctrl+Alt+M

It literally presses the following keys (after waiting for you to release Ctrl, Alt)

  • Ctrl+Home - cursor to top of file
  • Down - cursor to { line
  • Del Del - remove { and line
  • Ctrl+End - go to end
  • Bksp - remove }
  • Ctrl+a - select all
  • Shift+Tab - undent

I'm sure you can tweak the script as required; ; prefixing a line is a comment, ^!N:: is a hotkey ^ means Ctrl, ! means Alt, + means Shift.. Then the other keys are either {named} or literal chars

Related