Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get Visual Studio to use File Scoped namespaces by default

One of the changes to .Net, which cam in with .Net 6 I think, is the use of file scoped namespaces to reduce nesting.

I have created a solution containing .Net 8 project.

When I create a class using visual studio the default is to still nest the class within the namespace rather than use file scoped namespaces.

I expected it to default to file scoped namespaces as it was a .Net 8 project.

Is there a setting somewhere I need to alter?

like image 643
kevins1966 Avatar asked Dec 12 '25 19:12

kevins1966


2 Answers

Thanks for this.

You are right. I now realise I should have asked about "file scoped namespaces".

For clarification I found the full path to the option to be

Tools > Options> Text Editor > C# > Code Style > Code Block Preferences > Namespace Declarations = 'File scoped'.

I also found another solution at www.meziantou.net which was as follows

  • Set preference in the .editorconfig file.
  • If you don't have a .editorconfig file, create one at the root of the solution.
  • Put the following in the file
[*.cs]
csharp_style_namespace_declarations=file_scoped:suggestion

Which option should we go for

  • The former option would presumably need to be altered every time you worked on a solution which contained projects in version which do recognise file scoped namespaces
  • I guess the latter is preferable if you are hopping between working on solution of different versions
    • However if the solution contained projects at different versions, perhaps that might be problematic.

Any other considerations?

like image 167
kevins1966 Avatar answered Dec 15 '25 11:12

kevins1966


What you ask is file scoped namespaces, not top-level statements.

To use file scoped namespaces by default, go to Options, Code Style. In the Code Block Preferences block change Block Scoped to File Scoped. Code Block Preferences - Namespace declarations

like image 28
Panagiotis Kanavos Avatar answered Dec 15 '25 09:12

Panagiotis Kanavos



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!