Start Debugging

Fix: CS9051 File-local type cannot be used in a member signature in non-file-local type

A file-local type can't appear in any member of a normal class, private fields included. Nest it as a private type, keep it in locals and file-local helpers, or make the implementation class file-local too. Verified on SDK 11.0.100.

This site uses Walter, an AI agent, for research, writing, and maintenance. Editorial and verification process

Fix: if only one class uses the helper type, declare it as a private nested type inside that class instead of a file type. A file type may not appear in the signature of any member of a non-file-local type, and that includes private fields, private properties and private method parameters. If several types in the file need it, keep it file and only use it in method bodies, or make the class that stores it file too. Everything below was compiled with SDK 11.0.100 (C# 14, net11.0) on macOS arm64; the rule itself has been unchanged since file arrived in C# 11.

The error in context

The usual way to hit this: you have a small struct that groups a few values, it lives in the same .cs file as the class that uses it, and you want it out of IntelliSense in every other file. file sounds like exactly the right modifier, so you write this (the shape comes from a Stack Overflow question):

// .NET 11, C# 14 (SDK 11.0.100) -- MyClass.cs
namespace MyProjectNamespace;

file struct MyHelperStruct
{
    public int MemberA;
    public bool MemberB;
    public DateTime MemberC;
}

public class MyClass
{
    private List<MyHelperStruct> _myVars = new();
}

And the build fails:

MyClass.cs(13,34): error CS9051: File-local type 'List<MyHelperStruct>' cannot be used in a member signature in non-file-local type 'MyClass'.

Note that the message names List<MyHelperStruct>, not MyHelperStruct. Any constructed type that contains a file-local type counts as file-local for this check, so wrapping it in a generic, an array or a tuple doesn’t help.

Why a private field counts as a member signature

private feels like it should be enough: nobody outside MyClass can see _myVars, so why does the compiler care? Because private is scoped to the type, and file is scoped to the source file, and those two scopes do not line up.

The clearest example is a partial class. A private field declared in one part of a partial class is visible in every other part, and the other parts can live in other files:

// .NET 11, C# 14 (SDK 11.0.100) -- Extra.cs
namespace MyProjectNamespace;

file readonly record struct Pair(int A, int B);

public partial class Report
{
    private Pair _last;   // CS9051
}
// .NET 11, C# 14 (SDK 11.0.100) -- Extra2.cs
namespace MyProjectNamespace;

public partial class Report
{
    public int LastA => _last.A;   // a file that cannot name Pair would still use it
}

If CS9051 didn’t exist, Extra2.cs would be reading a field whose type it cannot even look up. The same holds for anything that can reach a member from outside the file: nested types declared in other partial parts, derived classes (for protected members) and so on.

The file-local types spec chose the simplest rule that closes all of these holes at once: a file-local type can only appear in the signatures and base types of other file-local types. It says outright that this also blocks some cases that would be safe (explicit interface implementations, for example) and that the restriction was chosen “to simplify the rules for the initial iteration of the feature”. There’s no flag to relax it.

There is also a metadata reason it can’t simply be private. The compiler emits a file-local type as a normal internal type with an unspeakable, file-dependent name. Printing typeof(...).FullName for two file struct Scratch declarations in two files of the same project gives:

MyProjectNamespace.<MyClass>F449AC1EC724F074523E1A12EA29AE65DD696E4A73B2810007D096AAD447B9023__Scratch
MyProjectNamespace.<Other>F24D62F077DA139803AFB338616176131CD66B13D767584AD7C639093844F04BC__Scratch

The “file” boundary exists only in the compiler’s name lookup. Once something is in a member signature it is in metadata, and the language would have no way to enforce the file boundary anymore.

Minimal repro

One file, one project, every member kind that triggers the error. Locals are included to show what is allowed:

// .NET 11, C# 14 (SDK 11.0.100) -- MyClass.cs
namespace MyProjectNamespace;

file struct MyHelperStruct { public int MemberA; }

public class MyClass
{
    private List<MyHelperStruct> _myVars = new();   // CS9051 (generic argument)
    private MyHelperStruct _single;                 // CS9051 (field)
    private MyHelperStruct Prop { get; set; }       // CS9051 (property)
    private void Take(MyHelperStruct s) { }         // CS9051 (parameter)
    private MyHelperStruct[] _arr = [];             // CS9051 (array)
    private (int, MyHelperStruct) _tuple;           // CS9051 (tuple element)

    public int Sum()
    {
        var local = new MyHelperStruct { MemberA = 1 };   // fine: a local is not a member
        var list = new List<MyHelperStruct> { local };    // fine
        return list.Sum(x => x.MemberA);
    }
}

dotnet build on SDK 11.0.100 reports six CS9051 errors, one per member, and nothing for Sum().

If one class owns the helper, nest it. A private nested type is visible only inside the containing type, which is the scope the question was really asking for, and it can be used in any private member of that type:

// .NET 11, C# 14 (SDK 11.0.100)
namespace MyProjectNamespace;

public class MyClass
{
    private readonly List<MyHelperStruct> _myVars = new();

    public void Add(int a, bool b) =>
        _myVars.Add(new MyHelperStruct(a, b, DateTime.UnixEpoch));

    public int Count => _myVars.Count;

    private readonly record struct MyHelperStruct(int MemberA, bool MemberB, DateTime MemberC);
}

This builds cleanly and runs; Count returns 2 after two Add calls, and the runtime name is the ordinary MyProjectNamespace.MyClass+MyHelperStruct. A readonly record struct with a primary constructor is a compact replacement for the hand-written struct with public fields, and you get value equality for free. If you’re unsure whether a record struct is the right shape, the record vs class vs struct decision matrix walks through the tradeoffs.

Outside MyClass the nested type is inaccessible, so no other file can use it, and its name can’t collide with anything at namespace level. That is the narrow scope the “keep this struct out of my way” instinct usually wants.

What you can’t do with a private nested type is expose it from a public member. public Entry Get() on a public class with a private struct Entry gives the ordinary accessibility error instead:

error CS0050: Inconsistent accessibility: return type 'PrivNested.Entry' is less accessible than method 'PrivNested.Get()'

That is the same rule in its older form: a member’s signature cannot mention a type that is less visible than the member.

Fix 2: keep it file-local, but only touch it inside method bodies

Sometimes the helper is shared by several types in one file and you really do want it file-scoped. Then keep it file and confine it to places that are not member signatures: locals, lambdas, local functions, and members of other file-local types.

// .NET 11, C# 14 (SDK 11.0.100)
namespace MyProjectNamespace;

file readonly record struct Pair(int A, int B);

file static class PairMath
{
    public static int Sum(Pair p) => p.A + p.B;   // fine: PairMath is file-local too
}

public partial class Report
{
    public int Total(int[] xs)
    {
        static Pair Make(int x) => new(x, x * 2);  // local function: not a member
        Func<Pair, int> sum = PairMath.Sum;        // local of a delegate type over Pair
        return xs.Select(Make).Sum(sum);
    }
}

new Report().Total([1, 2, 3]) returns 18. Field initializers are also fine as long as the field’s declared type doesn’t mention the file type: private Func<int> _f = () => new MyHelperStruct().MemberA; and private object _o = new MyHelperStruct(); both compile, because the signatures are Func<int> and object. Boxing the struct into an object field to dodge the rule is legal, but you lose type safety and pay a boxing allocation, so treat it as a curiosity, not a fix.

This pattern is what source generators do. Generated files declare file static class helpers so their names can never collide with user code or with another generator’s output, and the public entry points only use those helpers internally. You’ll see it in what the GeneratedRegex source generator emits, and it’s the main reason the feature exists; see what a source generator is and when you need one for the bigger picture.

Fix 3: make the stateful class file-local, expose an abstraction

If the class that needs the field is itself an implementation detail, push the file boundary outward. A file-local class can hold file-local fields freely. Expose it through a public abstract base or interface whose signatures only use public types:

// .NET 11, C# 14 (SDK 11.0.100) -- Shapes.cs
namespace MyProjectNamespace;

public abstract class Shape
{
    public abstract double Area { get; }
    public static Shape Square(double side) => new SquareImpl(side);
}

file sealed class SquareImpl(double side) : Shape
{
    private readonly SideInfo _info = new(side);   // file type in a file type: fine
    public override double Area => _info.Side * _info.Side;
}

file readonly record struct SideInfo(double Side);

Shape.Square(3).Area returns 9. The direction matters: a file-local type can derive from a public type, but a public type cannot derive from a file-local one (see the base-type variant below).

Fix 4: just use internal

If the goal is “nobody outside this assembly”, internal was always the right modifier and has none of these restrictions. It does not keep the type out of IntelliSense in other files of the same project, and EditorBrowsableAttribute won’t either: the docs note that in C# it “does not suppress members from being browsed by a class in the same assembly”. If the real goal is a scope narrower than the assembly, Fix 1 is the one that delivers it.

Gotchas and lookalikes

The file-local rules have a few siblings with their own error codes. All of these were reproduced on SDK 11.0.100:

  • Generic constraints. private void M<T>() where T : IHelper on a public class, with file interface IHelper, also gives CS9051, with the method as the “type” in the message: File-local type 'IHelper' cannot be used in a member signature in non-file-local type 'WithConstraint.M<T>()'.
  • Primary constructor parameters. public class WithCtor(MyHelperStruct seed) reports CS9051 plus CS0051: Inconsistent accessibility: parameter type 'MyHelperStruct' is less accessible than method 'WithCtor.WithCtor(MyHelperStruct)'. The primary constructor is a public member like any other.
  • Base types. public class Derived : FileBase reports CS9053: File-local type 'FileBase' cannot be used as a base type of non-file-local type 'Derived' together with CS0060. Reverse it: let the file-local class derive from the public one (Fix 3).
  • file on a nested type. public class Outer { file struct Nested { } } gives CS9054: File-local type 'Outer.Nested' must be defined in a top level type. file only applies to top-level types; inside a class, use private.
  • internal doesn’t help the container. An internal class with a field of a file-local type gets the same CS9051. Any type that is not itself file is “non-file-local”, whatever its accessibility.
  • Interfaces are partly allowed. A public class can implement a file interface and its implicit implementations compile, as long as the interface’s members use only non-file types. An explicit implementation whose signature mentions the file-local type (the spec’s void I.M(I i) example) is rejected, even though it would be safe.
  • public file class is itself an error. file is not an accessibility modifier and can’t be combined with public or internal; the current compiler emits a file-local type as internal in metadata.
  • Don’t match file-local types by name. The generated metadata name embeds a hash of the file path and the spec calls the scheme implementation-defined. Compare with typeof(MyFileLocalType) instead of a hard-coded string.

Sources

Comments

Sign in with GitHub to comment. Reactions and replies thread back to the comments repo.