what is the difference between 'protected' and 'private protected' access modifiers in C#? Can someone please explain with examples?
Thanks in advance.
what is the difference between 'protected' and 'private protected' access modifiers in C#? Can someone please explain with examples?
Thanks in advance.
It's about the acces modifier. More specific: inheritance and multiple assemblies. Consider the following:
For normal protected
(explained with along private
):
class Base
{
private bool X;
protected bool Y;
}
class A : Base
{
public void Foo()
{
X = false; //error: cannot access private member.
Y = true; //can access protected member, but only from classes with `: Base`
}
}
class B
{
public void Foo()
{
A a = new A();
a.X = false; //error: cannot access private member.
a.Y = false; //error: cannot access protected member.
}
}
Now the difference with private protected
is that it must live in the same assembly to be accessible:
So:
class A : Base
{
public void Foo()
{
X = false; //error: cannot access private member.
Y = true; //can access protected member, but only from classes with `: Base` AND
//they need to be defined in the same assembly as Base
}
}
Is valid, but only if both A
and Base
are compiled in the same assembly/dll/exe etc.
Now, since that clear, when would you use
an actual private protected
?
A lot can be said about this. Some (including me) would argue that the use of private protected
is an anti-pattern, because in my oppinion it's closly related to the friend keyword. And I must say, although in contradiction to friend
, private protected
keeps "the dirt" isolated, it still is arbitrary behavior, logic, depending on the location of it's definition.
Having said that the question remains, when to use it. You might be surprised I punctually used it once, and it was quite helpful.
Consider the following case:
graphical object
system..... then I would use private protected
;-)
Private protected is meant to allow the usage of protected member variables of a base class inside derived classes (children) within the same assembly only (same dot net dll).
This means that if you create a class inside an assembly A and you derive that class from another class defined in another assembly B, then your class from assembly A cannot have access to private protected member variables of class from assembly B.
However, using just protected modifier allow using protected member variables across different assemblies when deriving classes.
You can also take a look at the internal modifier which is a similar mechanism of protecting public variables across assemblies.