C# 10 File Scoped Namespaces - How to Migrate Your Project

One of the nice new features in C# 10 is file scoped namespaces.  It clears some of the cruft and provides more horizontal space for code instead of an extra indent.  If you are using Visual Studio 2022 or later you have a couple of nice options to apply this change at a page or project level.

At a page level, you can simply add a semi-colon at the end of your traditional using statement:

namespace ApiKeyAuthentication

VS will auto refactor this to

namespace ApiKeyAuthentication;

and remove the curly braces and indentation.

If you want to apply this to your entire project, follow these steps:

  1. Create a new file in your project root called .editorconfig (or use the existing file)
  2. Under Code Style search for namespace and select File Scoped
  3. Go to one of your traditional namespace declarations, right-click it and select "Quick Actions and Refactorings". You will see a list of all refactoring actions available, and one of them will be "Convert to file-scoped namespace". At the bottom, select Project and you’ll see a preview of the changes to be made. Then click Apply.
  4. Build your project and ensure there are no errors.

Need a developer, architect or manager? I am available - email me at [email protected]

Add comment