Access Modifiers in C#

Access modifiers are keywords used to specify the declared accessibility of a member or a type. Access modifiers are an integral part of OOPs. Encapsulation can be achieved using this, i.e. hiding functionality. Access modifiers allow you to define accessibility of member or type.

The following five accessibility levels can be specified using the access modifiers:
  1. Public: - Access is not restricted.
  2. Protected: - Access is limited to the containing class or types derived from the containing class.
  3. Internal: - Access is limited to the current assembly.
  4. Protected internal: - Access is limited to the current assembly or types derived from the containing class.
  5. Private: -Access is limited to the containing type.

Default Access Modifiers in C#:-
  • Namespaces implicitly have public declared accessibility. No access modifiers are allowed on namespace declarations.
  • Types declared in compilation units or namespaces can have public or internal declared accessibility and default to internal declared accessibility. (class, struct, interface, enum, delegate)
  • Class members can have any of the five kinds of declared accessibility and default to private declared accessibility.
  • (Note: - that a type declared as a member of a class can have any of the five kinds of declared accessibility, whereas a type declared as a member of a namespace can have only public or internal declared accessibility.)
  • Struct members can have public, internal, or private declared accessibility and default to private declared accessibility because structs are implicitly sealed. Struct members introduced in a struct (that is, not inherited by that struct) cannot have protected or protected internal declared accessibility.
  • (Note:-that a type declared as a member of a struct can have public, internal, or private declared accessibility, whereas a type declared as a member of a namespace can have only public or internal declared accessibility.)
  • Interface members implicitly have public declared accessibility. No access modifiers are allowed on interface member declarations.
  • Enumeration members implicitly have public declared accessibility. No access modifiers are allowed on enumeration member declarations.

Comments