Access modifiers are important to understand because we need to ensure that our classes are properly encapsulated. Remember the black box metaphor. Internals, or implementation details should be hidden from the outside world. We should only see the public interface.
We have the following access modifiers for members:
- public – accessible from everywhere
- private – accessible only from inside the class by other members
- protected – accessible only from inside the class and its derived classes
- internal – accessible from the same assembly
- protected internal – accessible from the same assembly and any derived classes (rarely, if ever needed)
Most of the time you will be using either public or private. You may use internal at times. The other two should rarely, if ever be used.
To understand the different access modifiers the best thing to do is to look at some examples.
Watch out for protected. It might be bad design. For example, you probably don’t need to allow classes derived from the class to have access to the member.
Protected internal is a bit complicated and you should really never use it unless you have good reason to use it.