Understanding C# the "file" modifier/keyword in class definitions

Posted: (EET/GMT+2)

 

The most recent C# version 11 (as in .NET 7.0) introduced the file modifier, which lets you restrict a type so it's only visible inside the source file where it has been declared.

This is useful when you need helper types that should not be accessed from the rest of the assembly, or you are generating code with a tool and want to make sure there are no conflicts with the rest of the project. The file modifier makes intent clear and avoids accidental reuse or naming conflicts.

A simple example:

file class Helper
{
    public static int Add(int a, int b)
    {
        return a + b;
    }
}

public class Calculator
{
    public int Sum(int x, int y)
    {
        return Helper.Add(x, y);
    }
}

In this case, the Helper class is only visible inside the same source file. Other files in the project cannot reference it, even though it is in the same assembly.

You can also use file with interfaces or other top-level types:

file interface IWorker
{
    int Work();
}

file class Worker : IWorker
{
    public int Work() => 42;
}

Types declared as file avoid naming conflicts because other files can define types with the same name without collisions. The file-local type is only visible within its own source file.

Summary: this modifier is especially useful for small helper classes, source generator output, or implementation details that should stay private to a single file.