protected private access modifier in C# 7.2
C# 7.2 introduces new access modifier – protected private. It targets developers who are responsible for class libraries and API-s design and who need also consistent design for internals of class libraries. This blog post shows how protected private access modifier works.
- Non-trailing named arguments in C# 7.2
- protected private access modifier in C# 7.2
Source code available! Those who want some basic samples of new features can take my solution from GitHub repository gpeipman/CSharp7. This is (almost) the same solution I’m using for presentations.
What is protected private?
Let’s start with comparing previous protected access modifiers and see what level of access to class member they allow:
- protected – member is accessible to all classes that extend the given class no in which assembly extending class is defined,
- protected internal – member is accessible to all class that extend the given class and to all other classes in same assembly.
For class library developers there are was no way how to make class members inheritable only to classes in same assembly and same time restrict internal access. To support this scenario C# 7.2 introduces protected private access modifier:
- protected private – member is accessible only to classes that extend the given class and are located in same assembly.
Let’s get now to some examples illustrating protected internal and protected private.
What was private internal allowing too much was access to member by classes in same assembly. Let’s define the following dummy class.
public class PrivateInternalExample
protected internal void Dummy()
Also let’s define another dummy demo class that uses the one we just defined.
public class DemoOfPrivateInternal
public void Demo()
var x = new PrivateInternalExample();
Take a careful look – DemoOfPrivateInternal class doesn’t extend PrivateInternalExample class but it is still able to access Dummy() method.
Let’s make same experiment with protected private now.
Before building and getting errors we already see in Visual Studio IDE that we can’t access protected private from another class without extending the class where it is defined.
protected private access modifier is small language feature that mostly affects those who are working on widely used class libraries or class libraries used by other teams. It gives more freedom on library design and express better author intensions with class usage also when it is about internals of class library.
4 thoughts on “protected private access modifier in C# 7.2”
Pingback:The Morning Brew - Chris Alcock » The Morning Brew #2585
private protected is an abomination. :(
Not necessarily.API-s that have big internal part not exposed to API clients can benefit of this feature.
Dear Gunnar! Am I write if I put both of them like this?
protected Internal (is equal to) protected OR internal
protected private (is equal to) protected AND internal