Advertisement
Advanced C#, Modern C# Features (Global Usings, File-Scoped Namespaces, Top-Level Statements)

How does the 'file' access modifier (C# 11) create a type visible ONLY within its own source file, and what problem does this solve for source generators?

Short answer

The 'file' modifier restricts a type's visibility to ONLY the file it's declared in — even other classes in the SAME namespace and assembly can't see or reference it — specifically designed to let source generators emit HELPER types with common, simple names (like 'Helpers' or…

Save C# mock interview
Advertisement
AModel answer
The 'file' modifier restricts a type's visibility to ONLY the file it's declared in — even other classes in the SAME namespace and assembly can't see or reference it — specifically designed to let source generators emit HELPER types with common, simple names (like 'Helpers' or 'Constants') across many generated files WITHOUT any risk of naming collisions between them.
// GeneratedFile1.g.cs
file class Helpers { public static string Format(string s) => s.Trim(); } // invisible outside this file

// GeneratedFile2.g.cs
file class Helpers { public static int Format(int n) => n; } // a DIFFERENT, non-conflicting 'Helpers' type
Real-world example
Understanding why source-generator-emitted code can safely reuse simple, common type names across many generated files without collisions.
Likely follow-ups
  • Would a regular 'private' or 'internal' modifier have been sufficient to solve this same naming-collision problem?
Related topics