Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

VS 2022 - Convert to file-scoped namespace in all files

I'm converting my project to .NET 6 and I want to use filescoped namespaces everywhere. But the conversion tool exists only in the editor.

file-scoped namespace conversion

Has anyone found out if there's a way to run this editor function across all files in solution at once? (Looks like Rider has that function)

like image 745
Mirek Avatar asked Nov 08 '21 20:11

Mirek


3 Answers

Adding a rule to use file scoped namespaces in .editorconfig worked for me:

  • create an .editorconfig file in the solution directory
  • add following line/content below (docs, code - IDE0161)

Example .editorconfig file content:

[*.cs]
csharp_style_namespace_declarations = file_scoped:warning

After that the preview changes dialog had an option to apply the fix to the whole project/solution:

enter image description here

like image 164
Guru Stron Avatar answered Oct 09 '22 11:10

Guru Stron


I always have problems finding files that are supposed to be updated (.editorconfig in this case). I don't even know if I should search for it in the project's, Visual Studio installation's or any folder on the PC. So I like the answer in the link below because it says where in the interface to change the setting.

Best answer in my opinion is here: https://www.ilkayilknur.com/how-to-convert-block-scoped-namespacees-to-file-scoped-namespaces

It says that you can change the code-style preference (and enable the display of the option to apply this preference in a document / project / solution) by going to Tools => Options => Text Editor => C#=> Code Style and then changing the related preference. enter image description here

like image 18
Emilija Vilija Trečiokaitė Avatar answered Oct 09 '22 11:10

Emilija Vilija Trečiokaitė


EditorConfig syntax

csharp_style_namespace_declarations = file_scoped
dotnet_diagnostic.IDE0161.severity = error

Note

Syntax option = rule:severity will be deprecated, sooner or later.

I strongly recommend to read this article before you start build .editorconfig for your project.

like image 6
KUTlime Avatar answered Oct 09 '22 11:10

KUTlime