Skip to content

File local types C# 11.0code generation

Restrict a type so it can only be referenced from the file it is declared in.

In order to avoid collisions with other types (such as when generating code) you can prefix a type with the file keyword to indicate it can only be referenced from the file it is defined in.

The usual workaround was to make the type internal and give it a machine-generated suffix such as CantBeSeenOutside234456aze, so that a generator running in several files would not produce duplicate definitions. That works, but it leaks the type into the assembly's internal surface and the name is just noise in stack traces and IntelliSense. A file type gets a mangled name automatically and cannot collide.

Code ​

csharp
file class CantBeSeenOutside
{
}

// The same name in another file is a different type
file class Helper
{
    public static void Run() { }
}
csharp
internal class CantBeSeenOutside234456aze
{
}

// Had to invent unique names per file
internal class Helper1
{
    public static void Run() { }
}

Notes ​

  • A file type can't appear in the signature of a member of a non-file type, as it would then be visible outside the file; the compiler reports CS0050 for inconsistent accessibility
  • The type is still usable anywhere inside its own file, including inside a method body
  • Two file types with the same name are legal in different files, because each is compiled into a distinct mangled type name; declaring the same name twice in one file is CS9071
  • It can be combined with partial, so a generator can declare a file partial type and the developer can add members in the same file
  • Applies to classes, structs, interfaces, enums, delegates and records, but not to members - there is no file-scoped method or property
  • See File-scoped namespaces C# 10.0 for the complementary change that removes the namespace indentation rather than the visibility.

More information ​

Powered by Intracia