We're starting a new mini-series today, one that covers some of the upcoming features and changes that C# 10 is going to bring. Let's dive into the first of these, a feature which (like several others in this series) is supposed to make our C# files less cluttered: file-level namespaces.

Background

A lot of the changes coming in C# 10 are designed to make our code files less cluttered. The C# team is doing this primarily by making certain assumptions that appear to be common in nearly every C# project.

In this particular case, we most often have a single namespace defined in any given C# file. Since that is so often the case, we can use a file-level namespace to clear out a bit of noise from our C# files.

Current Implementation

At the moment, namespaces are implemented using curly braces:

namespace MyNamespace
{
    public class MyClass
    {
        public void MyMethod()
        {
            //...Method implementation
        }
    }
}

Any C# object which exists within the curly braces also exists within the specified namespace. We can access those objects by explicitly specifying the namespace, or by utilizing a using statement:

var object = new MyNamespace.MyClass();
using MyNamespace;

var object = new MyClass();

New Implementation

With this change, we will now be able to implement a namespace and have it apply to the entire file where it exists:

namespace MyNamespace;

public class MyClass
{
    public void MyMethod()
    {
        //...Method implementation
    }
}

The invocation of objects within the namespace will not change:

var object = new MyNamespace.MyClass();
using MyNamespace;

var object = new MyClass();

Other Considerations

The only real drawback I see in this implementation is that, when using file-level namespaces, you cannot have two namespaces in the same file. Most of the time, though, I can't really see this being a big issue, since that's normally what happens anyway.

Demo Project

Although file-level namespaces are not yet included in the C# 10 preview, I have included a sample of how they might work in the sample project for this series:

GitHub - exceptionnotfound/CSharp10Features
Contribute to exceptionnotfound/CSharp10Features development by creating an account on GitHub.

Happy Coding!