File-Scoped Namespaces

C# 10.0 .NET 6.0

Published Updated Author Jeffrey T. Fritz Reading time

File-scoped namespaces declare a namespace at the file level with a simple semicolon syntax, eliminating unnecessary indentation and making code cleaner and easier to read.

Introduced in C# 10.0, file-scoped namespaces simplify the common pattern of having a single namespace per file. Instead of wrapping the entire file content in a namespace block, you declare the namespace once at the top with namespace MyNamespace; and it applies to all code in that file. This reduces nesting and improves readability.

Why it matters

File-scoped namespaces eliminate one level of indentation and make files easier to scan. Since most C# files contain exactly one namespace, this feature reduces boilerplate significantly. The cleaner structure improves code readability and is now the recommended pattern for most new C# projects.

Cautions

File-scoped namespaces only work when there is a single namespace per file. If you need multiple namespaces in one file (an uncommon but valid pattern), you must use traditional block-scoped namespaces. Additionally, file-scoped namespaces cannot be mixed with block-scoped namespaces in the same file, which may require refactoring legacy code.

Using file-scoped namespaces

File-scoped namespaces eliminate indentation and reduce nesting, applying the namespace to the entire file with a single declaration.

Valid since C# 10.0

// UserService.cs - using file-scoped namespace (C# 10.0)
namespace MyApp.Services;

public class UserService
{
    public void PrintUser(string name)
    {
        Console.WriteLine($"User: {name}");
    }
}

// Logger class in the same file-scoped namespace
public class Logger
{
    public void Log(string message)
    {
        Console.WriteLine($"[LOG] {message}");
    }
}

Comparison with traditional namespaces

See how file-scoped namespaces simplify code structure compared to traditional block-scoped namespaces.

Valid since C# 10.0

// TRADITIONAL BLOCK-SCOPED NAMESPACE (pre-C# 10.0)
/*
namespace MyApp.Services
{
    public class UserService
    {
        public void PrintUser(string name)
        {
            Console.WriteLine($"User: {name}");
        }
    }
}
*/

// FILE-SCOPED NAMESPACE (C# 10.0+)
namespace MyApp.Services;

public class UserService
{
    public void PrintUser(string name)
    {
        Console.WriteLine($"User: {name}");
    }
}

// Benefits:
// - Cleaner indentation
// - Simpler visual structure
// - Less nesting required
// - Modern, recommended approach

Learn more

File-Scoped Namespaces (Microsoft Learn)