Search code examples
c#visual-studio-codeomnisharp

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://learn.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

  • 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)

    EDIT (Dec 22nd):

    For VS Code, I have installed "C# Extensions" by JosKreativ

    Once installed, go to: File > Preferences > Settings

    In the "Search settings" textbox type "namespace"

    You'll see the option (for me 3rd);

    "Csharpextensions: Use File Scoped Namespace"

    Check that checkbox and you're good to go.