Advertisement
Intermediate C# Programming, Access Modifiers in C#

Can we use all access modifiers for all types?

Short answer

No, not every access modifier can be applied to every kind of type or member. For example, top level classes and interfaces defined directly within a namespace can only be declared as either public or internal, not private or protected, since private and protected only make…

Save C# Programming mock interview
Advertisement
AModel answer
No, not every access modifier can be applied to every kind of type or member. For example, top level classes and interfaces defined directly within a namespace can only be declared as either public or internal, not private or protected, since private and protected only make sense in the context of a containing type. Members declared inside a class, on the other hand, can use the full range of access modifiers, including private, protected, internal, public, and protected internal.
// Valid: top level class as public or internal
public class Order { }
internal class InternalHelper { }

// Not valid: top level class cannot be private
// private class Invalid { }
Real-world example
A developer attempting to declare a top level helper class as private receives a compiler error, and instead marks it as internal, since the class is only meant to be used within the same project assembly.
Likely follow-ups
  • Why can't top level classes be declared as private or protected?
  • What access modifiers are valid specifically for interface members?
Related topics