2

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).

8
  • Just checking: Class1 isn't a partial class or anything like that? Commented Mar 2, 2024 at 15:50
  • I presume that having the variable as a private member makes it accessible to the outside world via reflection, whereas a variable inside a method cannot escape. Commented Mar 2, 2024 at 15:54
  • 1
    "Why" is not a good question. Please clarify what kind of answer you are expecting. Commented Mar 2, 2024 at 15:55
  • @Sweeper Something like "the reason for this is ______" Commented Mar 2, 2024 at 15:59
  • 2
    @Sweeper Can you stop being pedantic? If you want, you go ahead and edit my question. I think it's pretty clear. Commented Mar 2, 2024 at 16:03

2 Answers 2

1

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 { } 
Sign up to request clarification or add additional context in comments.

2 Comments

Could you rephrase a bit this answer? I am not sure to understand what "signature" means here. I know about "signature" in the context of a method, but it does not look like this is the right context. In other words, even after reading the spec, I don't understand why a private class member could not be file-scoped.
They are referring to signatures of any member type (even for private members), which includes your private field (at least that's how I understand it, even if it is not clear to me why this affects private members).
-2

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

1 Comment

Both the classes in the example code are in the same file.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.