C# Access Modifiers

tutorial and example
tutorial and example

C# provides various keywords to control or restrict accessibility or scope of the data. We can apply access modifiers to functions and variables.

There are five access modifiers in C#:

  1. Private
  2. Protected
  3. Internal
  4. Protected internal
  5. Public

Let’s see each one of them in detail:

Access Modifier Description
public Public variable is accessible everywhere
Protected Protected is accessible only in derived class
Internal Internal is accessible only in containing assembly
Protected internal It is accessible in current assembly or derived classes.
Private It is only accessible within class

Public Access modifier:

It makes data which is accessible publically. It doesn’t restricts the scope of data.

 Example:

Output

Protected Access Modifier:

we can access protected modifier within the class or outside the class by inheritance.

Example:

Output

Protected Access modifier: Accessing data through inheritance

Output

Private Access Modifier:

Private can only be accessed within class only. it is the most restricted Access Modifier.

Example:

Output

Internal Access Modifier:

Internal access modifier enables you to access the variable within the current assembly.

Example:

Protected Internal access Modifier:

The protected internal variable can be accessed inside assembly as well as in the other assembly by inheritance.

Example:

Output