Skip to main content

Documentation Index

Fetch the complete documentation index at: https://docs.syntblaze.com/llms.txt

Use this file to discover all available pages before exploring further.

A file-scoped namespace is a C# 10 language feature that applies a namespace declaration to all types within a single source file without requiring enclosing braces. By terminating the namespace declaration with a semicolon rather than a code block, it alters the lexical structure of the file and eliminates an indentation level for all subsequent type declarations.

Syntax Comparison

Traditional Block-Scoped Namespace:
namespace Company.Project.Module
{
    public class Processor
    {
        // Indented code
    }
}
File-Scoped Namespace:
namespace Company.Project.Module;

public class Processor
{
    // Unindented code
}

Compiler Rules and Constraints

The C# compiler enforces strict structural rules when parsing file-scoped namespaces:
  1. Single Declaration Limit: A source file can contain a maximum of one file-scoped namespace declaration.
  2. Mutual Exclusivity: A file cannot mix file-scoped namespaces and block-scoped namespaces. If a file-scoped namespace is declared, no namespace { ... } blocks are permitted in that same file.
  3. Placement Precedence: The file-scoped namespace declaration must precede all type declarations (classes, structs, interfaces, enums, delegates) in the source file.
  4. No Sequential Nesting: You cannot declare multiple file-scoped namespaces sequentially to achieve nesting.
Invalid:
namespace Company;
namespace Project; // Compiler error: Source file can only contain one file-scoped namespace
Valid:
namespace Company.Project; // Use dot notation for nesting

Interaction with using Directives

using directives can be placed either before or after a file-scoped namespace declaration. Both placements are syntactically valid, though they carry the same scoping implications as they would with a block-scoped namespace.
using System; // Valid

namespace Company.Project.Module;

using System.Linq; // Valid

public class Processor { }

Intermediate Language (IL) Equivalence

File-scoped namespaces are purely syntactic sugar. During compilation, the Roslyn compiler translates a file-scoped namespace into the exact same Intermediate Language (IL) as a block-scoped namespace. There is no runtime difference, metadata difference, or reflection difference between types declared using either syntax.
Master C# with Deep Grasping Methodology!Learn More