Skip to main content
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:
File-Scoped Namespace:

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:
Valid:

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.

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.
Tired of Poor C# Skills? Fix That With Deep Grasping!Learn More