I was quite interested while reading the article about how methods and properties with access specifiers as
internal in other
assembly/binaries can be accessed. The purpose of the access specifier
internal is to have the access level only within the same Assembly in which they are
created. But still, is it possible to access the types and members with internal scope in some other assembly? The answer is
We have the attribute named
InternalsVisibleTo, which makes the solution for accessing internal types and members of some other assembly easier.
The types and members with the access specifier
internal (C#) or
Friend scope (Visual Basic) are visible only
in the assembly in which they are defined.
InternalsVisibleTo attribute makes internal types and members visible to the types in a specified assembly, which is known as a friend assembly.
The attribute is applied at the assembly level. This means that it can be included at the beginning of a source code file, or it can be
included in the AssemblyInfo file in a Visual Studio project.
How to specify InternalsVisibleTo Attribute
We can use the
InternalsVisibleTo attribute to specify a single friend assembly that can access the internal types and members of the current assembly as mentioned below.
If we have multiple assemblies, then we can declare multiple friend assemblies in two ways as explained below.
Points to remember
- We need to add the namespace
System.Runtime.CompilerServices to define
- Both the current assembly and the friend assembly must be unsigned, or both assemblies must be signed with a strong name.
- If they are signed with a strong name, the argument to the
attribute constructor must include the full public key as well as the name of the assembly.
[assembly: InternalsVisibleTo ("Assembly1, PublicKey=002400000480000094" +
§ "0000000602000000240000525341310004000" +
§ "001000100bf8c25fcd44838d87e245ab35bf7" +
§ "3ba2615707feea295709559b3de903fb95a93" +
§ "3d2729967c3184a97d7b84c7547cd87e435b5" +
§ "6bdf8621bcb62b59c00c88bd83aa62c4fcdd4" +
§ "712da72eec2533dc00f8529c3a0bbb4103282" +
§ "f0d894d5f34e9f0103c473dce9f4b457a5dee" +
§ "fd8f920d8681ed6dfcb0a81e96bd9b176525a" +
Code snippets from the sample
public class ClassB
internal static void Method1()
Console.WriteLine("Method1() in ClassB is called.");
internal static string GetName()
return ClassC.Name; }