Home » C# Access Modifiers

C# Access Modifiers

by Online Tutorials Library

C# Access Modifiers / Specifiers

C# Access modifiers or specifiers are the keywords that are used to specify accessibility or scope of variables and functions in the C# application.

C# provides five types of access specifiers.

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

We can choose any of these to protect our data. Public is not restricted and Private is most restricted. The following table describes about the accessibility of each.

Access Specifier Description
Public It specifies that access is not restricted.
Protected It specifies that access is limited to the containing class or in derived class.
Internal It specifies that access is limited to the current assembly.
protected internal It specifies that access is limited to the current assembly or types derived from the containing class.
Private It specifies that access is limited to the containing type.

Now, let’s create examples to check accessibility of each access specifier.


1) C# Public Access Specifier

It makes data accessible publicly. It does not restrict data to the declared block.

Example

Output:

Hello Shantosh Kumar Hello Peter Decosta 

2) C# Protected Access Specifier

It is accessible within the class and has limited scope. It is also accessible within sub class or child class, in case of inheritance.

Example

Output:

Compile time error 'ProtectedTest.name' is inaccessible due to its protection level. 

Example2

Here, we are accessing protected members within child class by inheritance.

Output:

Hello Shashikant Hello Swami Ayyer 

3) C# Internal Access Specifier

The internal keyword is used to specify the internal access specifier for the variables and functions. This specifier is accessible only within files in the same assembly.

Example

Output:

Hello Shantosh Kumar Hello Peter Decosta 

4) C# Protected Internal Access Specifier

Variable or function declared protected internal can be accessed in the assembly in which it is declared. It can also be accessed within a derived class in another assembly.

Example

Output:

Hello Shantosh Kumar Hello Peter Decosta 

5) C# Private Access Specifier

Private Access Specifier is used to specify private accessibility to the variable or function. It is most restrictive and accessible only within the body of class in which it is declared.

Example

Output:

Compile time error 'PrivateTest.name' is inaccessible due to its protection level. 

C# Private Specifier Example 2

Output:

Hello Shantosh Kumar Hello Peter Decosta 

Next TopicC# Encapsulation

You may also like