Access Modifiers

All class members have access modifiers. We already encountered them when we decorated our classes with the public keyword.

Access modifiers define a context in which a given class or its member can be used.

  • The public modifier makes a class or its member public to all external code. They can be accessed from any other part of the program and even from a different program or assembly.
  • The private modifier makes a class or its member closed to the external environment. A private class can only be accessed from the class where it’s defined. We can’t make a class private on the namespace level. Members that are private can only be accessed from within the class where they’re defined.
  • The protected modifier can only be used with class members. These members are only accessible from the same class or any derived class.
  • With the internal modifier, classes and members are only visible inside the assembly where they’re defined.

Note: An assembly is a collection of types (classes, structs, and so on). It’s essentially a .dll or an .exe file that results from compiling our project. One .NET project equals one assembly.

  • The protected internal modifier indicates that classes and members are accessible from the current assembly and from any derived class (including those residing in other assemblies).
  • The private protected modifier indicates that members are visible inside the class where they’re defined and inside the derived classes in the current assembly.

Let’s explore each of the modifiers with the help of the code playground.

The public modifier

Get hands-on with 1400+ tech skills courses.