Why can't I declare a private member of a file-local type in another class within the same file?

60 Views Asked by At

This code:

public class Class1
{
    private Class2 _class2;

    private void Something()
    {
        Class2 class2;
    }
}

file class Class2
{

}

produces compiler error CS9051 on the member _class2 but not on the local variable class2 inside the method:

File-local type 'Class2' cannot be used in a member signature in non-file-local type 'Class1'.

Clicking on the link provided with CS9051 opens this page, which at the time of this writing states Sorry, we don't have specifics on this C# error. I couldn't find anything else on the web which explains why this is the case. Can someone please explain why I can use Class2 inside of a method or property within Class1 but not as a private class member? It seems like this reduces the usefulness of an otherwise-useful feature (the file access modifier).

2

There are 2 best solutions below

1
urlreader On

Permit a file modifier on top-level type declarations. The type only exists in the file where it is declared.

https://learn.microsoft.com/En-Us/dotnet/csharp/language-reference/proposals/csharp-11.0/file-local-types

0
Olivier Jacot-Descombes On

The proposal says Only allow signature usage in members of file-local types. There is also an example showing your use case.

A workaround is to type the fields as object and to cast the field when using it:

public class Class1
{
    private object _class2 = new Class2();

    private void Something()
    {
        Class2 class2 = (Class2)_class2;
    }
}

file class Class2
{

}