Friday, October 25, 2024

C# Protected Internal Access Modifier


In C#, the protected internal access modifier is used to control the visibility and accessibility of members (fields, methods, properties, etc.) within a class hierarchy. This access modifier combines the functionality of both protected and internal access modifiers.

Here's a breakdown of what protected internal means:

1. Protected Access Modifier: The protected access modifier restricts access to the member to within its containing class or derived classes. In other words, a protected member can be accessed by the same class or any class derived from it.

2. Internal Access Modifier: The internal access modifier restricts access to the member to the current assembly. It allows access from any code in the same assembly but not from code in other assemblies.

3. Protected Internal Access Modifier: The protected internal access modifier combines the accessibility of both protected and internal. It allows access to the member from:
  • Within the same assembly (like internal), and
  • Within a derived class (like protected), regardless of whether the derived class is in the same assembly OR a different assembly.
In summary, a protected internal member can be accessed within the current assembly and by derived classes both within the current assembly and in other assemblies.

Here's an example demonstrating the usage of protected internal:
// In AssemblyA

public class BaseClass
{
    protected internal int ProtectedInternalMember { get; set; }
}

// In AssemblyB (a different assembly)

public class DerivedClass : BaseClass
{
    public void AccessProtectedInternalMember()
    {
        // Can access protected internal member from the derived class
        int value = ProtectedInternalMember;
    }
}

// In any code within AssemblyA

BaseClass baseObject = new BaseClass();
baseObject.ProtectedInternalMember = 42; // Can access within the same assembly

DerivedClass derivedObject = new DerivedClass();
derivedObject.ProtectedInternalMember = 42; // Can access from a derived class even in a different assembly
In this example, DerivedClass can access the ProtectedInternalMember inherited from BaseClass because it is both derived and in the same assembly. Other classes within the same assembly can also access the ProtectedInternalMember.

No comments:

Post a Comment

Hot Topics