Tom
Tom

Reputation: 167

How to remove curly braces from a namespace

I would like to know how I can remove the braces from a namespace and have it be closed with a semicolon (;).

actually:

namespace ProductsGroup{
  public void save{
  }
}

I need:

namespace ProductsGroup;
  public void save{
  }

Upvotes: 10

Views: 15387

Answers (1)

Richard
Richard

Reputation: 109130

Visual-Studio 2022 already offers this refactoring (and the reverse).

Additionally you can set a preference in Visual Studio's C# Code Style settings, and in .editorconfig.

More details: https://www.ilkayilknur.com/how-to-convert-block-scoped-namespacees-to-file-scoped-namespaces

Update: The above assumes valid code

In the question you have:

namespace ProductsGroup{
  public void save{
  }
}

which is not valid in any version of C#.

Top level functions can be used, but not with a namespace (all top level functions end up in a class, named based on the filename, in the root namespace).

Otherwise you need a type. So you can refactor:

namespace MyNamename {
  public class MyClass {
    public Task MyAsync() {
      // ...
    }
  }
}

to/from

namespace MyNamename;
public class MyClass {
  public Task MyAsync() {
    // ...
  }
}

Upvotes: 15

Related Questions