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.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.
Syntax Comparison
Traditional Block-Scoped Namespace:Compiler Rules and Constraints
The C# compiler enforces strict structural rules when parsing file-scoped namespaces:- Single Declaration Limit: A source file can contain a maximum of one file-scoped namespace declaration.
- 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. - Placement Precedence: The file-scoped namespace declaration must precede all type declarations (classes, structs, interfaces, enums, delegates) in the source file.
- No Sequential Nesting: You cannot declare multiple file-scoped namespaces sequentially to achieve 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.
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





