Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 360
Pablo Marambio Avatar asked Oct 15 '08 15:10

Pablo Marambio


People also ask

What is the protected access modifier used for?

The protected modifier specifies that the member can only be accessed within its own package (as with package-private) and, in addition, by a subclass of its class in another package.

What is the use of protected internal?

protected internal: The type or member can be accessed by any code in the assembly in which it's declared, or from within a derived class in another assembly. private protected: The type or member can be accessed by types derived from the class that are declared within its containing assembly.

What is internal access modifier?

Internal is one of the access modifiers that limits the access to types defined within the current project assembly. The default accessibility of classes and structs that are declared within a namespace or at the top level of a compilation unit and not within other types is internal.

What's the difference between protected and internal What about protected internal?

The type or member can be accessed by any code in the same assembly, but not from another assembly. protected internal: The type or member can be accessed by any code in the assembly in which it is declared, OR from within a derived class in another assembly.


1 Answers

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.

like image 187
Jeff Yates Avatar answered Sep 28 '22 06:09

Jeff Yates