concept InternalsVisibleTo in category c#

appears as: The InternalsVisibleTo, InternalsVisibleTo
Code like a Pro in C#

This is an excerpt from Manning's book Code like a Pro in C#.

First, the [assembly: InternalsVisibleTo([assembly name])] attribute, which you can only apply to namespaces, allows a different assembly (the FlyingDutchmanAirlines_Tests.ServiceLayer assembly in our case) to access and manipulate private and internal methods, properties, and fields of the containing assembly (FlyingDutchmanAirlines). When the CLR sees the InternalsVisibleTo attribute, it notes the given assembly and designates it as a “friend” assembly to the one it is trying to access the internals of. In practical terms, The CLR treats a friend assembly as the same assembly as the containing assembly when it comes to compiling down to Intermediate Language.

The problem with using friend assemblies and the InternalsVisibleTo attribute approach is that the InternalsVisibleTo attribute is incredibly finicky to deal with. There are oodles of pages on stack overflow with questions about how to get the attribute working correctly. Besides the usability issue, we also aren’t very keen on testing private methods. Ideally, we would test all private methods through public methods that use them. Tests should not walk any paths that a normal user would not walk. Since a normal user does not interact with a class by calling its private methods, neither should a unit test. The InternalsVisibleTo method attribute is a good thing to know about, but not a practical thing to use. The real “Pro Tip”, when it comes to InternalsVisibleTo, is to save yourself the heartache of using it and just don’t.

C# in Depth

This is an excerpt from Manning's book C# in Depth.

In .NET 1.1 it was entirely accurate to say that something defined to be internal (whether a type, a method, a property, a variable, or an event) could only be accessed within the same assembly in which it was declared.[3] In .NET 2.0 that’s still mostly true, but there’s a new attribute that lets you bend the rules slightly: InternalsVisibleToAttribute, usually referred to as just InternalsVisibleTo. (When applying an attribute whose name ends with Attribute, the C# compiler will apply the suffix automatically.)

7.7.2. Why use InternalsVisibleTo?

I rarely use InternalsVisibleTo between two production assemblies. I can see how it could be useful, and I’ve certainly used it for extra access when writing tools, but my primary use of it has always been unit testing.