What’s New in C# 10: Reclaim Horizontal Editing Space and Simplify Nesting

This is the first part in a series on the new features introduced with C# 10.

Prior to C# 10, to define types as being part of a specific namespace you would use the following syntax:

namespace ConsoleAppCS9
{
    public class SomeClass
    {
        public void SomeMethod(bool b, string s)
        {
            if (b is true)
            {
                if (s is not null)
                {
                    // do something
                }
            }
        }
    }
    namespace SomeNestedNamespace
    {
        public class AClassInANestedNamespace
        {
            // etc.
        }
    }
}

 

With C# 10 we can use something called file-scoped namespace declarations.

All this means is that we can remove one level of nesting in { } brackets:

namespace ConsoleAppCS9;

public class SomeClass
{
    public void SomeMethod(bool b, string s)
    {
        if (b is true)
        {
            if (s is not null)
            {
                // do something
            }
        }
    }
}

The line namespace ConsoleAppCS9; means that any types defined in that one file will be inside the ConsoleAppCS9 namespace.

This has the effect in the editor of giving us more horizontal editing space and nesting to keep mental track of.

Also note in the second example that you can’t have nested namespaces in the file if file-scoped namespace declarations are being used – in this case you’d have to return to the traditional namespace syntax.

If you want to fill in the gaps in your C# knowledge be sure to check out my C# Tips and Traps training course from Pluralsight – get started with a free trial.

SHARE:

Add comment

Loading