Private Protected in C#: What It Means and How to Use It
private protected is an access modifier that allows a class member to be accessible only within its own class or derived classes that are in the same assembly. It combines the restrictions of private and protected, making it more restrictive than protected internal but less restrictive than private alone.How It Works
Think of private protected as a special door that only certain people can open. It lets access to a class member only if you are inside the same building (assembly) and you are either the owner of the room (the class itself) or a close family member (a derived class).
This means that if you have a class member marked private protected, it is hidden from everyone outside the assembly, even if they inherit from the class. But inside the assembly, derived classes can use it freely.
This access level is useful when you want to keep things hidden from the outside world but still allow some controlled access within your own code base and its subclasses.
Example
This example shows a base class with a private protected member and a derived class in the same assembly accessing it. Another class outside the assembly cannot access it.
using System;
namespace AssemblyA
{
public class BaseClass
{
private protected string secretMessage = "Hello from private protected!";
public void ShowMessage()
{
Console.WriteLine(secretMessage);
}
}
public class DerivedClass : BaseClass
{
public void DisplaySecret()
{
// Accessing private protected member inside derived class in same assembly
Console.WriteLine(secretMessage);
}
}
class Program
{
static void Main()
{
DerivedClass obj = new DerivedClass();
obj.DisplaySecret(); // Works
BaseClass baseObj = new BaseClass();
baseObj.ShowMessage(); // Works
}
}
}When to Use
Use private protected when you want to hide class members from all code outside your assembly but still allow derived classes within the same assembly to access them. This is helpful in large projects where you want to keep your internal workings private but allow controlled extension by subclasses.
For example, if you are building a library and want to let subclasses inside your library access certain data or methods, but prevent external users or subclasses outside your library from accessing them, private protected is the right choice.
Key Points
private protectedrestricts access to the containing class and derived classes within the same assembly.- It is more restrictive than
protected internalbut less restrictive thanprivate. - Useful for hiding implementation details from outside code while allowing subclass access inside the assembly.
- Introduced in C# 7.2 to provide finer control over member accessibility.
Key Takeaways
private protected limits access to the class itself and derived classes in the same assembly.