What is protected internal in C#: Explanation and Example
protected internal is an access modifier that allows a class member to be accessed from any code in the same assembly or from derived classes in other assemblies. It combines the behaviors of both protected and internal access modifiers.How It Works
Think of protected internal as a special door that opens in two ways: one for friends inside your house (the same assembly) and another for family members (derived classes) even if they live in a different house (another assembly). This means the member is accessible anywhere inside the same project, plus in any subclass that inherits from it, even if that subclass is in a different project.
This access level is useful when you want to share functionality broadly within your own codebase but still allow extensions by subclasses outside it. It blends the rules of protected (accessible in subclasses) and internal (accessible within the same assembly) so you get the benefits of both.
Example
This example shows a base class with a protected internal member accessed from a subclass in the same assembly and from another class in the same assembly.
using System;
namespace ExampleNamespace
{
public class BaseClass
{
protected internal string message = "Hello from protected internal!";
}
public class DerivedClass : BaseClass
{
public void ShowMessage()
{
Console.WriteLine(message); // Access allowed because of protected internal
}
}
public class OtherClass
{
public void ShowMessage()
{
BaseClass baseObj = new BaseClass();
Console.WriteLine(baseObj.message); // Access allowed because same assembly (internal part)
}
}
class Program
{
static void Main()
{
DerivedClass derived = new DerivedClass();
derived.ShowMessage();
OtherClass other = new OtherClass();
other.ShowMessage();
}
}
}When to Use
Use protected internal when you want to allow access to class members both within your own assembly and to any subclasses outside it. This is helpful in large projects where you want to keep some parts hidden from the public but still extendable by inheritance.
For example, if you are building a library and want to let other developers extend your classes while keeping some members hidden from general use, protected internal is a good choice. It balances encapsulation and flexibility.
Key Points
- protected internal means accessible within the same assembly or by derived classes anywhere.
- It combines
protectedandinternalaccess rules. - Useful for sharing code inside a project and allowing subclassing outside.
- Helps control visibility while supporting inheritance.
Key Takeaways
protected internal allows access inside the same assembly and in derived classes outside it.protected and internal access modifiers.