internal vs protected in C#
By Tan Lee Published on Mar 05, 2025 186
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.
Categories
Popular Posts
Freedash bootstrap lite
Nov 13, 2024
10 Common Mistakes ASP.NET Developers Should Avoid
Dec 16, 2024
Gentella Admin Template
Nov 14, 2024