We recommend using Visual Studio 2017
This documentation is archived and is not being maintained.

How to: Create Unsigned Friend Assemblies (C# and Visual Basic)

This example shows how to use friend assemblies with assemblies that are unsigned.

To create an assembly and a friend assembly in Visual Studio

  1. Open a Visual Studio command prompt.

  2. Create a Visual Basic or C# file named friend_signed_A. that contains the following code. The code uses the InternalsVisibleToAttribute attribute to declare friend_signed_B as a friend assembly.

    ' friend_unsigned_A.vb
    ' Compile with: 
    ' Vbc /target:library friend_unsigned_A.vb
    Imports System.Runtime.CompilerServices
    Imports System
    <Assembly: InternalsVisibleTo("friend_unsigned_B")> 
    ' Friend type.
    Friend Class Class1
        Public Sub Test()
        End Sub
    End Class
    ' Public type with Friend member.
    Public Class Class2
        Friend Sub Test()
        End Sub
    End Class
  3. Compile and sign friend_signed_A by using the following command.

    Vbc /target:library friend_unsigned_A.vb

    csc /target:library friend_unsigned_A.cs
  4. Create a Visual Basic or C# file named friend_unsigned_B that contains the following code. Because friend_unsigned_A specifies friend_unsigned_B as a friend assembly, the code in friend_unsigned_B can access Friend (Visual Basic) or internal (C#) types and members from friend_unsigned_A.

    ' friend_unsigned_B.vb
    ' Compile with: 
    ' Vbc /r:friend_unsigned_A.dll friend_unsigned_B.vb
    Module Module1
        Sub Main()
            ' Access a Friend type.
            Dim inst1 As New Class1()
            Dim inst2 As New Class2()
            ' Access a Friend member of a public type.
        End Sub
    End Module
  5. Compile friend_signed_B by using the following command.

    Vbc /r:friend_unsigned_A.dll friend_unsigned_B.vb

    csc /r:friend_unsigned_A.dll /out:friend_unsigned_B.exe friend_unsigned_B.cs

    The name of the assembly that is generated by the compiler must match the friend assembly name that is passed to the InternalsVisibleToAttribute attribute. You can explicitly set the assembly by using the /out compiler option.

    In C#, you must explicitly specify the name of the output assembly (.exe or .dll) by using the /out compiler option. In Visual Basic, this is optional. For more information, see /out (Visual Basic) and /out (C# Compiler Options).

  6. Run the friend_signed_B.exe file.

    The program prints two strings: "Class1.Test" and "Class2.Test".

There are similarities between the InternalsVisibleToAttribute attribute and the StrongNameIdentityPermission class. The main difference is that StrongNameIdentityPermission can demand security permissions to run a particular section of code, whereas the InternalsVisibleToAttribute attribute controls the visibility of Friend (Visual Basic) or internal (C#) types and members.