Friend Assemblies

A friend assembly can access another assembly's Friend (Visual Basic) or internal (C#) types and members. If an assembly is identified as a friend assembly, the types and members no longer have to be marked as public in order to be accessed by other assemblies.

How can you identify friend assemblies for a given assembly?

The attribute InternalsVisibleToAttribute can be used to identify one or more friend assemblies for a given assembly. The InternalsVisibleToAttribute class specifies that types that are ordinarily visible only within the current assembly are visible to a specified assembly.

Note: When an assembly that will access internal types or internal members of another assembly is compiled, the name of the output file (.exe or .dll) must be explicitly specified by using the /out compiler option.
Explicit naming of output file is required because at the time of binding to external references, the compiler has not yet generated the name for the assembly it is building.

Example: The following example uses the InternalsVisibleToAttribute attribute in assembly A and specifies assembly AssemblyB as a friend assembly. This gives assembly AssemblyB access to all types and members in assembly A that are marked as Friend (Visual Basic) or internal (C#).

using System.Runtime.CompilerServices;
using System;

[assembly: InternalsVisibleTo("AssemblyB")]

// The class is internal by default.
class FriendClass
{
    public void Test()
    {
        Console.WriteLine("Sample Class");
    }
}

// Public class that has an internal method.
Public class ClassWithFriendMethod
{
    internal void Test()
    {
        Console.WriteLine("Sample Method");
    }
} 
Validation Rules for friend assembly name passed to the InternalsVisibleToAttribute attribute (If assembly A declares B as a friend assembly)
  • If assembly A is strong named, assembly B must also be strong named. The friend assembly name that is passed to the attribute must consist of the assembly name and the public key of the strong-name key that is used to sign assembly B (the assembly version, culture, architecture, or public key token should not be included).
  • If assembly A is not strong named, the friend assembly name should consist of only the assembly name.
  • If assembly B is strong named, you must specify the strong-name key for assembly B by using the project setting or the command-line /keyfile compiler option.

No comments:

Post a Comment