In response to one of interview questions at the earlier post dot net interview questions,this post is dedicated to various access modifiers in C#.
Basically Microsoft .NET framework provides following access modifiers via the CTS.
- Public : The member is accessible to any code in any assembly. There are no restrictions in accessing the public members and this modifier is the most permissive.
- Private : The member is accessible only by other members in the same class type. This is least permissive modifier.The member can be accessed only from within the body of class or struct in which they are declared.
- Internal (Assembly): The member is accessible by any code in the same assembly but not from any other assembly. A common usage is in component development where whole library of classes can be coded inside same assembly and those classes doesn’t get exposed to code using the component.
- Protected (Family): The member is accessible within same type just like private. It is also accessible by derived types, regardless of whether they are within the same assembly.
Members of structures cannot be declared as protected since inheritance is not allowed in structures.
- Protected internal (Family OR assembly): The member is accessible by derived types in any assembly. The member is also accessible by any types in the same assembly. Please note the keywords “family or assembly” which describes it is accessible by assembly neighbors and family members.
- Family and assembly: The member is accessible by derived types, but only if the derived type is defined in the same assembly. This modifier is not supported by C# however it is supported by CTS.
Some important things to note about access modifiers
- Only public or internal is allowed for non nested classes, structs and interfaces. Internal is the default modifier in this case.Private is default in case of nested classes, structs and interfaces.
- Access level for class and struct members is private by default.
- Accessibility of derived types can never be greatar than that of base class.
- Access modifiers are not allowed on destructors.
- Members of enumeration are always public and no access modifier is allowed on enum.
- For delegates, same accessibility rules apply as those of classes.