C# 10 introduces file scoped namespaces. This allows you to remove the ‘{}’ when your source file only has one namespace(like most files typically have).
So instead of writing:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
namespace ExampleApp | |
{ | |
class ExampleClass | |
{ | |
} | |
} |
you can now write:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
namespace ExampleApp; | |
class ExampleClass | |
{ | |
} |
To apply this for an existing project written in C# 9 or lower, you can do this in one go.
Therefore set the language version of your project to C# 10:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<Project Sdk="Microsoft.NET.Sdk"> | |
<PropertyGroup> | |
<TargetFramework>net6.0</TargetFramework> | |
<LangVersion>10</LangVersion> | |
</PropertyGroup> | |
</Project> |
Now we need to update our .editorconfig file and add the following line:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
[*.cs] | |
csharp_style_namespace_declarations=file_scoped:suggestion |
After doing that Visual Studio will help us out and we can use “Fix all occurences in Solution” to apply it in one go:
No comments:
Post a Comment