Search code examples
.netencapsulationaccess-modifiers

When would you use the "protected internal" access modifier?


As you may already know, the .NET Framework's protected internal access modifier works in a strange way: It doesn't mean the class is protected AND internal, it says the class is protected OR internal; that is, the modified class or member can be accessed from whitin the same assembly as well as from the same hierarchy.

So, knowing this: When would you use it? Can you give an example? Is there a good, illuminating usage example inside .NET Base Class Library?


Solution

  • I have rarely needed to use this access modifier combination as I think that in all but the most extreme circumstances, it's an indicator of poor design. However, sometimes it is necessary to have helper classes like type converters and editors access the method inside your assembly, but only allow derived classes to access it in other use cases.

    An example might be a call that turns a type into a string for the type converter. ToString() generally isn't used for this purpose so you might have a ToPersistableString() call that you want your type converter to use, so you make it internal. Then you decide that people deriving from your class may well want to use this call as part of their own persistence scheme for their derived class so you make it protected as well.

    .NET Framework Use
    AccessibilityNotifyClients on Control is protected internal. Using Reflector, I can see that this was done so that the CheckedItemCollection of CheckListBox could access it when changing checked states.