Wednesday, August 18, 2021

C# 10.0: Introducing File Scoped Namespaces

C# 10.0 is expected to ship with .NET 6 in November, 2021 during .NET Conf 2021 (November 9-11), but some of the features are already available with C# preview LangVersion. In this post let's have a look at File Scoped Namespaces that got shipped with .NET 6 Preview 7 SDK last week.

To try out this feature you will need to use the latest Visual Studio 2022 Preview, which includes the latest .NET 6.0 preview SDK, or alternatively, you can install .NET 6 Preview 7 SDK and use the latest Visual Studio Code.

You can set the LangVersion as preview in your csproj file as follows.

<Project Sdk="Microsoft.NET.Sdk">

  <PropertyGroup>
    ...
    <LangVersion>preview</LangVersion>
  </PropertyGroup>

</Project>

Now, this is how we are defining namespaces.

namespace ConsoleApp1.Models
{
    
public class SomeClass
    {
    }
}

So what's the issue with this. Well, there is no technical issue, but this is adding unnecessary indentation to the code and you might have experienced this: when the class becomes longer, you sometimes lose track of indentation. So less indentation is always the best.

Starting with C# 10, you can do something like this.

namespace ConsoleApp1.Models;

public class SomeClass
{
}

Notice the introduction of semicolon after the namespace and the removal of curly braces after the namespace. That's just one less indentation.  

Personally, this is one of my favorite features in C# 10. Hope this helps.

Happy Coding.

Regards,
Jaliya

No comments:

Post a Comment