internal vs protected in C#
By Tan Lee Published on Mar 05, 2025 99
The access modifiers public and private are straightforward: public means everything has access, while private restricts access solely to the class itself.
However, the internal
and protected
modifiers are a bit more complicated.
- Use
internal
when you want to restrict access to only within the same assembly. - Use
protected
when you want to limit access to the class itself and its subclasses.
In simpler terms, internal
makes something "private" to the assembly, while protected
makes it "private" to the class and its subclasses.
Key Differences:
- Access Scope:
internal
: Accessible within the same assembly.protected
: Accessible within the class and its subclasses, even across different assemblies.
- Usage Context:
internal
is ideal for limiting access within a single assembly or module.protected
is useful when you want to provide access to derived classes while keeping members hidden from external code.
For example:
// 'internal' example public class Bird { internal void Fly() { Console.WriteLine("Bird is flying."); } } // 'protected' example public class Bird { protected void Fly() { Console.WriteLine("Bird is flying."); } } public class Sparrow : Bird { public void TestFly() { // Can access protected method in derived class Fly(); } }
In the internal
example, the Fly()
method is only accessible within the same assembly. In the protected
example, Fly()
is accessible in the Sparrow
subclass, even though Sparrow
could be in a different assembly.
- Primitive types in C#
- How to set permissions for a directory in C#
- How to Convert Int to Byte Array in C#
- How to Convert string list to int list in C#
- How to convert timestamp to date in C#
- How to Get all files in a folder in C#
- How to use Channel as an async queue in C#
- Case sensitivity in JSON deserialization
Categories
Popular Posts
Horizon MUI Admin Dashboard Template
Nov 18, 2024
Elegent Material UI React Admin Dashboard Template
Nov 19, 2024
Dash UI HTML5 Admin Dashboard Template
Nov 18, 2024
Material Lite Admin Template
Nov 14, 2024