Access Modifiers

Master the usage of C# access modifiers to control the visibility and encapsulation of classes and their members across different assemblies and inheritance hierarchies.

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

Access modifiers control the visibility and scope of classes and their members.

  • The public modifier makes a class or member visible to all external code. Any part of the program, including code in different assemblies, can access them.

  • The private modifier restricts access to the containing class. Private members are accessible only from within the class where they are defined.

  • The protected modifier can only be used with class members. These members are only accessible from the same class or any derived class.

  • The internal modifier ensures classes and members are only visible inside the assembly where they are defined.

Note: An assembly is the compiled output of our code. In modern .NET, one project usually results in one assembly (a .dll file). The internal modifier ensures code is only visible to other classes within that same project.

  • 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 are defined and inside derived classes in the current assembly only.

Let’s explore each of the modifiers.

The public modifier

We marked the Car class as public. This modifier allows code in other namespaces and projects to access the class. All we need to do is import the required namespace and add a project reference if needed.