Pro EP 95 : Have you heard about file Access Modifier in C# ?

Muhammad Waseem
Become .NET Pro !
2 min readDec 25, 2023

Access modifiers guide in C# with file type modifier ?

𝐏𝐮𝐛𝐥𝐢𝐜:
Use when you want a member to be accessible from any part of your code.

𝐏𝐫𝐢𝐯𝐚𝐭𝐞:
Use when you want a member to be accessible only within the declaring class or struct.

𝐏𝐫𝐨𝐭𝐞𝐜𝐭𝐞𝐝:
Use when you want a member to be accessible within the declaring class or in derived classes.

𝐈𝐧𝐭𝐞𝐫𝐧𝐚𝐥:
Use when you want a member to be accessible within the same assembly but not from other assemblies.

𝐏𝐫𝐨𝐭𝐞𝐜𝐭𝐞𝐝 𝐈𝐧𝐭𝐞𝐫𝐧𝐚𝐥:
Use when you want a member to be accessible within the same assembly or from derived classes.

𝐏𝐫𝐢𝐯𝐚𝐭𝐞 𝐏𝐫𝐨𝐭𝐞𝐜𝐭𝐞𝐝:
Use when you want a member to be accessible within the same assembly and by derived classes, but only if they are in the same assembly.

𝐅𝐢𝐥𝐞:
Beginning with C# 11, the file contextual keyword is a type modifier.

1/ Restricts the scope and visibility of a top-level type to the file in which it’s declared.

2/ Typically used with types generated by source generators to prevent naming collisions.

3/ Types declared with the file modifier, including nested types, are only visible within the file where they are declared.

4/ File-local types cannot be used as return or parameter types in members with greater visibility, and they can’t be field members of types with greater visibility. However, more visible types can implicitly implement file-local interfaces. Explicit implementations are allowed but limited to file scope.

Whenever you’re ready, there are 4 ways I can help you

  1. Subscribe to my Weekly .NET Newsletter of C#/.NET with 8000+ Software Engineers.
  2. Promote yourself to 8000+ subscribers by Sponsoring my Newsletter
  3. Download my eBook at Gum Road which contains 30+ .NET Tips (With 2800+ Downloads)
  4. To get 100+ free and paid resources for learning C# and .NET visit this GitHub Repository

--

--