Access modifiers in C#.NET

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.

  1. 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.
  2. 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.
  3. 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.
  4. 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.

  5. 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.
  6. 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

  1. 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.
  2. Access level for class and struct members is private by default.
  3. Accessibility of derived types can never be greatar than that of base class.
  4. Access modifiers are not allowed on destructors.
  5. Members of enumeration are always public and no access modifier is allowed on enum.
  6. For delegates, same accessibility rules apply as those of classes.

References:

  1. MSDN
  2. CLR via C#
DZoneDeliciousLinkedInRedditTechnorati FavoritesStumbleUponShare

2 comments

  1. [...] Answer: Its “family or assembly”. Other one is not supported by C#. Refer more here: Access modifiers in C#.NET [...]

  2. Access modifiers in C#.NET…

    You’ve been kicked (a good thing) – Trackback from DotNetKicks.com…

Leave a Reply

Your email address will not be published. Required fields are marked *