CodeSteps

Python, C, C++, C#, PowerShell, Android, Visual C++, Java ...

C# – Access Modifiers – protected access modifier

protected access modifier in C# restricts the access to, access the class and it’s members within the class, the class where it is defined and it’s derived classes ONLY. In C# we use protected keyword to declare a class or it’s members as protected members.

protected Access Modifier

We CAN NOT create a protected class directly in the namespace. We can create the protected classes, ONLY within another class. If you attempt to create a protected class inside the namespace, you will get the below Error:

Error 1 Elements defined in a namespace cannot be explicitly declared as private, protected, or protected internal

As mentioned above, protected access modifier defines the scope of the class or it’s members to be accessible within the class itself, or the class where it is defined or it’s derived classes. We can not access protected members beyond this scope. Due to this, we CAN NOT access protected members from another namespace or from another Assembly. If you attempt to return protected members using public methods of the class, you will get below Error: Hence you have to be more cautious when you deal with private and protected members.

Error 1 Inconsistent accessibility: return type ‘xyz’ is less accessible than method ‘abc’

Here I am giving an example, to get more clarity on the usage of protected access modifier in C#.

We discuss more topics as we go.

(Raju)

C# – Access Modifiers – protected access modifier

Leave a Reply

Your email address will not be published. Required fields are marked *

Scroll to top