Access Modifiers
Learn to control the visibility of methods and other class members.
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 aclass
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 aclass
or its member closed to the external environment. A privateclass
can only be accessed from theclass
where it’s defined. We can’t make aclass
private on thenamespace
level. Members that areprivate
can only be accessed from within theclass
where they’re defined. - The
protected
modifier can only be used withclass
members. These members are only accessible from the sameclass
or any derivedclass
. - 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 derivedclass
(including those residing in other assemblies). - The
private protected
modifier indicates that members are visible inside theclass
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.