If you’re using Visual Studio 2022 & want to use File-scoped namespaces (C# 10+) by default when you create a new class set the ‘Namespace declarations’ preference to ‘File scoped’ as shown below …
Note however these are local user settings.
When in a team environment it is better to use an EditorConfig file to enforce settings across an entire solution or project for all devs.
You can generate an .editorconfig file from the settings above using the button highlighted in blue.
The relevant line if you just want file scoped namespaces as a preference is …
csharp_style_namespace_declarations = file_scoped
but if you actually want Visual Studio to cause compile time errors if you don’t use file-scoped namespaces the syntax would be …
csharp_style_namespace_declarations = file_scoped:error
3 thoughts on “How to set C# 10+ file scoped namespaces as default in Visual Studio”
Tried this and I still get an error that my ‘file scoped namespace’ is not available in C# 7.3. Please use language version 1.0 or greater.
I’m using VS 2022
I created a blank solution.
I added a project “Empty Project (.NET Framework) using .NET Framework 4.8.
Added a code file. Then added this code:
public static class AverageCalculator
And I immediately get the error.
To expand on rosdi’s comment, C# 10 is only available in .NET 6 and above. When developing for .NET Framework you are by default limited to C# 7.3. Although you can access some of the newer features by manually setting the compiler/language version and adding the appropriate nuget packages, this will only take you so far. Some new features require changes to the CLR which are not compatible with .NET Framework at any level.
The .NET Framework is on life support at this point. If you have any control over the .NET version you’re using (which we don’t always have the luxury of, for various reasons) then I strongly suggest you migrate your projects to .NET 6 or 7. It’s a bit of a moving target with even long-term support versions (LTS, currently the even numbered major releases) lasting only 3 years. But upgrading between .NET versions isn’t usually too much of a hassle: change the version, look for any new warnings, run tests and commit the changes and you’re about done.
As stated in the title. This is only supported in C# 10 or greater.