Pages

Topics

Tools

↑↓navigate↵openescclose
All guides

C# File Local Type: Scoped Type Declarations

C# file-local types restrict type visibility to a single source file. Learn how they work, when to use them, and which constraints apply.

~6 min readC#
#C# 11#file-local types#type scoping#C# accessibility
Illustration of a C# source file containing a type that is enclosed within a file boundary, representing file-local type scoping.

C# file-local types, introduced in C# 11, let you declare a type whose visibility is restricted to the file in which it is declared. The file modifier can be applied to classes, structs, interfaces, enums, records, and delegates. This is a compile-time accessibility feature, not a runtime construct. The generated IL for a file type may include a generated unique name to prevent collisions, but the language guarantees that the type is only accessible within the same source file.

Consider a common problem: a large file contains several helper types that are implementation details. Without file, these types are either public (polluting the public API) or internal (visible to the entire assembly). With file, you can make the helper type visible only to the code in that specific source file. That is particularly useful when you want to avoid cluttering the assembly's internal namespace and prevent other files in the same assembly from depending on a type that is meant for one file.

How to Declare a File-Local Type

Applying the file modifier is straightforward. Place it before the type declaration, and combine it with other modifiers only when allowed. For example, a file class cannot have a higher accessibility than file itself, so you cannot use public or internal together with file.

csharp
file class Helper { public static int Square(int x) => x * x; } file struct Coordinate { public int X { get; set; } public int Y { get; set; } } file interface ICalculator { int Add(int a, int b); }

You can also apply file to a nested type, though the nested type is still visible only within the same file.

csharp
public class DataProcessor { file struct ProcessingContext { public int Offset; public int Count; } }

In this example, ProcessingContext is accessible only within the file that contains the DataProcessor class. Code in another file cannot reference it, even code that is part of the same partial class declaration.

Why the File Modifier Is Useful

Many large C# projects face the problem of internal types that are used only in a single file. Previously, you had to mark them internal, which makes them visible to everything in the same assembly. That visibility sometimes encourages coupling: other files might start using a type that was never intended for them, making future refactoring harder. The file modifier gives you a more precise scope. It also helps in source-generator and code-generation scenarios, where you want to generate helper types that must not collide with user types or other generated types.

Another real-world benefit appears in unit testing. Test projects sometimes have helper classes that are needed only in one test file. Marking them file prevents accidental reuse across test files and keeps each test file self-contained. This reduces hidden dependencies between test fixtures.

Rules and Constraints

The file modifier is valid only on type declarations, not on methods, properties, events, or local functions. You can apply it to a type at the top level of a compilation unit, inside a namespace, or nested in another type. A non-file type cannot derive from a file type, and a file type cannot be used as a base type for a non-file type, because either form would widen the visibility of the file type.

Consider the following illegal code:

csharp
file class Base { } public class Derived : Base { } // Error: cannot use a file-local type as a base type

Even when both declarations are in the same file, the compiler rejects this declaration because Derived is not file-local and would widen the visibility of Base.

A file interface can inherit from another file interface in the same file, but a non-file interface cannot inherit from a file interface.

Here is a summary of key constraints:

ConstraintExplanation
ScopeAccessible only within the same source file.
Modifier compatibilityCannot be combined with public, internal, protected, or private.
Nested typesAllowed, but the nested type's scope is still the file.
Base typesCannot be used as a base type for a non-file type.
Default visibilityA file type is effectively file-scoped; no other modifier is needed.

Runtime Behavior and Type Identity

At compile time, the compiler gives each file-local type a unique metadata name, often by appending a hash or unique identifier to the type name. This lets two files in the same assembly declare a file type with the same simple name without conflict. For example:

csharp
// File1.cs file class Cache { } // File2.cs file class Cache { }

Both files can define a Cache class, and the compiler creates distinct types in the assembly. Source code in each file sees only its own Cache; the other version is not available outside its file. Reflection can inspect the generated types, but the exact metadata names are compiler-generated and should not be relied on. Code that looks up a type by its simple source name will not find it.

Maintaining Type Safety With File-Local Types

One advantage is that file-local types are ordinary types within their file. They work in method signatures, local functions, lambda expressions, and generic type inference without reflection or dynamic dispatch. The compiler enforces the same type safety as with any other type. For example:

csharp
public class Processor { file record ParsedData(string Name, int Value); public object Process(string input) { ParsedData data = Parse(input); return data; } private ParsedData Parse(string input) { // ... parsing logic return new ParsedData(input, input.Length); } }

Here, ParsedData is used only within the same file, but it still provides strong compile-time typing. Process returns object because the public method cannot expose the file-local type directly. Inside the file, the code avoids returning a loosely typed tuple or object for the private parsing path.

Edge Cases and Common Mistakes

One common mistake is trying to split a file type across multiple files with partial. A file-local type is scoped to one compilation unit, so its partial declarations cannot be merged across files. The compiler rejects such code.

Another mistake is exposing a file type as the return type of a method whose accessibility domain is wider than the file. The compiler disallows that because callers outside the file cannot see the type. For instance:

csharp
file class Hidden { } public class Exposer { public Hidden GetHidden() => new Hidden(); // Error: return type is less accessible than method }

A method itself cannot be marked file; file applies only to type declarations. To return a file-local type, the method's effective accessibility domain must stay within the file. For example, make the method private, make the containing type file-local, or change the return type to an accessible type.

Compatibility Considerations

The file modifier is available in C# 11 and later. file is a contextual keyword, so code that uses file as an identifier is still valid in many positions, but the compiler recognizes it as the file-local modifier on type declarations. In earlier language versions, the modifier is not recognized.

The feature is enforced by the compiler, not by the runtime, so the scoping behavior itself does not require a particular .NET runtime version. It does require a C# 11-capable compiler and a project configured to use C# 11 or later.

When to Use File-Local Types

Use a file type when you have a type that is an implementation detail of a single file, and you want to prevent other developers from accidentally using it. If the type is genuinely an internal helper that could be reused across files, internal is still the right choice. The file modifier is not a replacement for internal; it is a stricter alternative for a narrow scenario.

Consider a large data transformation file that has a private helper class for parsing a temporary format. If you mark that helper internal, it becomes accessible to all other files in the same assembly, which may be unnecessary. Using file keeps the parsing logic truly private to that file. If you later need to share that helper with another file, you must remove the file modifier and adjust visibility, an explicit action that forces you to consider the design.

For source generators, file types are beneficial because they let a generator emit a type with the same name across multiple generated files without worrying about collisions. Each generated file is a separate source file in the compilation, so each gets its own unique type and no naming conflict occurs.

Try matching browser tools

All tools

Small utilities that fit C# work — they run entirely in this browser tab, so nothing you paste leaves your device.

All C# guides

More in C#

All C# guides

The guides filed next to this one in C#, in library order.