Breaking

Monday, November 29, 2021

C# 10–Change an existing project to file scoped namespaces

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:

namespace ExampleApp
{
class ExampleClass
{
}
}
view raw ExampleClass.cs hosted with ❤ by GitHub

you can now write:

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:

<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:

[*.cs]
csharp_style_namespace_declarations=file_scoped:suggestion
view raw .editorconfig hosted with ❤ by GitHub

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