.NET, Archive, Software Design

The Wonders Of InternalsVisibleTo

Jason / November 8, 2007

I do not know how I missed this, but just today I found out that you can expose an assembly’s internal methods/properties/classes to a "friend" assembly. Normally internals are only accessible to members of the same assembly, and are often used to hide "plumbing" methods and utilities classes.

For many reasons you often want to separate your code into multiple assemblies, perhaps one for each application layer or some other logical boundary. A problem arises when two or more assemblies need access to each others internals. Prior to .NET 2.0 you had two choices, either expose these plumbing methods as public, or lump as much of your code into one assembly as was needed to keep the plumbing internal.

In comes .NET 2.0’s InternalsVisibleTo attribute. This attribute is applied on the assembly level, and allows the assembly to give internal access to specific assemblies.

For example:

Say you have two assemblies, MyExample.DomainObjects & MyExample.ServiceLayer. In the DomainObjects assembly you have the following abstract class:

namespace MyExample.DomainObjects{
public abstract class DomainObject{
//.... other things....
public virtual DateTime LastModifiedDate{
get { ... }
internal set { ... }
}
}
}
read more