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
publicmodifier makes a class or member visible to all external code. Any part of the program, including code in different assemblies, can access them.The
privatemodifier restricts access to the containing class. Private members are accessible only from within the class where they are defined.The
protectedmodifier can only be used withclassmembers. These members are only accessible from the sameclassor any derivedclass.The
internalmodifier 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 internalmodifier indicates that classes and members are accessible from the current assembly and from any derivedclass(including those residing in other assemblies).The
private protectedmodifier indicates that members are visible inside theclasswhere 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.