Start Debugging
2023-03-18 Updated 2023-11-05 csharp

C# 11 – file access modifier & file-scoped types

Learn how the C# 11 file access modifier restricts a type's scope to the file in which it is declared, helping avoid name collisions with source generators.

The file modifier restricts a type’s scope and visibility to the file in which it is declared. This is especially useful in situations where you want to avoid name collisions among types – like in the case of generated types using source generators.

A quick example:

file class MyLocalType { }

In terms of restrictions we have the following:

On the other hand:

Implementing a file-scoped interface implicitly

A public class can implement a file-scoped interface as long as they are defined in the same file. In the example below you have the file-scoped interface ICalculator which is implemented by a public class Calculator.

file interface ICalculator
{
    int Sum(int x, int y);
}

public class Calculator : ICalculator
{
    public int Sum(int x, int y) => x + y;
}
< Back