Access Modifiers

In this lesson, we will learn about the access modifiers and how to use them in our C# code.

In C#, we can impose access restrictions on different data members and member functions. The restrictions are specified through access modifiers. Access modifiers are tags we can associate with each member of the class to define which of its parts can be accessed by the program/application directly.

Types of Access Modifiers

There are the following six types of access modifiers in C#:

  1. private
  2. public
  3. protected
  4. internal
  5. protected internal
  6. private protected

We’ll only discuss private and public for now. The rest of the access modifiers will be discussed in the upcoming chapter on inheritance.

Private

A private modifier is used with a class member to specify that its access is limited to the code inside of the containing class only. In other words, private members can only be accessed by the methods of that class. A private member cannot be accessed directly from outside the class.

If we don’t specify any access modifier with a class member, it is recognized as private by default.

The aim is to keep it hidden from users and other classes. It is a popular practice to keep data members private since we do not want anyone manipulating our data directly. We can make members private by using the keyword private.

Get hands-on with 1200+ tech skills courses.