views:

1635

answers:

2

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?

+4  A: 

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.

Jeff Yates
+1  A: 

I've used it for internal methods that you wanted to be able to use in a separate name space for unit testing, the unit test name space contained a subclass of the class. which allowed the protected methods to be accessed.

That said there is an argument to make everything public for unit testing.

Omar Kooheji