Practical uses for the "internal" keyword in C#

Alexander Prokofyev picture Alexander Prokofyev · Oct 3, 2008 · Viewed 202.1k times · Source

Could you please explain what the practical usage is for the internal keyword in C#?

I know that the internal modifier limits access to the current assembly, but when and in which circumstance should I use it?

Answer

Ash picture Ash · Oct 3, 2008

Utility or helper classes/methods that you would like to access from many other classes within the same assembly, but that you want to ensure code in other assemblies can't access.

From MSDN (via archive.org):

A common use of internal access is in component-based development because it enables a group of components to cooperate in a private manner without being exposed to the rest of the application code. For example, a framework for building graphical user interfaces could provide Control and Form classes that cooperate using members with internal access. Since these members are internal, they are not exposed to code that is using the framework.

You can also use the internal modifier along with the InternalsVisibleTo assembly level attribute to create "friend" assemblies that are granted special access to the target assembly internal classes.

This can be useful for creation of unit testing assemblies that are then allowed to call internal members of the assembly to be tested. Of course no other assemblies are granted this level of access, so when you release your system, encapsulation is maintained.