Share via


Making Friends in the CLR

My boss and I were lamenting the lack of the "friend" declaration in the CLR languages like C# this week.

We're working on tightening up the Publishing API for the MTPS system (the publishing system behind msdn2.microsoft.com) and wanted to be able to restrict access to some utility library methods so that only the core of the system could use them but not external clients. "What we need," I said "is C++'s 'friend' declaration. Too bad we don't have that for managed code."

Turns out we do have such functionality. Even better, maybe.

Using the [assembly:InternalsVisibleTo] attribute introduced in .NET 2.0 allows to to declare another assembly a "friend," meaning that all members declared with internal visibility can be accessed from the friend assembly. Pretty neat. It solved our problem quite well. I'm not sure how I missed this when .NET  2.0 came out, but I did.

Note that there are some important security caveats to keep in mind when using this attribute.