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

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?



Solution 1:[1]

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

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Caius Jard