What is the difference between 'protected' and 'protected internal'?
Can someone please explain the difference between the protected
and protected internal
modifiers in C#? It looks like their behavior is identical.
Solution 1:
The "protected internal" access modifier is a union of both the "protected" and "internal" modifiers.
From MSDN, Access Modifiers (C# Programming Guide):
protected:
The type or member can be accessed only by code in the same class or struct, or in a class that is derived from that class.
internal:
The type or member can be accessed by any code in the same assembly, but not from another assembly.
protected internal:
The type or member can be accessed by any code in the assembly in which it is declared, OR from within a derived class in another assembly. Access from another assembly must take place within a class declaration that derives from the class in which the protected internal element is declared, and it must take place through an instance of the derived class type.
Note that: protected internal
means "protected
OR internal
" (any class in the same assembly, or any derived class - even if it is in a different assembly).
...and for completeness:
private:
The type or member can be accessed only by code in the same class or struct.
public:
The type or member can be accessed by any other code in the same assembly or another assembly that references it.
private protected:
Access is limited to the containing class or types derived from the containing class within the current assembly.
(Available since C# 7.2)
Solution 2:
protected
can be used by any subclasses from any assembly.
protected internal
is everything that protected
is, plus also anything in the same assembly can access it.
Importantly, it doesn't mean "subclasses in the same assembly" - it is the union of the two, not the intersection.