Sponsored Ad

Wednesday, October 21, 2009

C# Friend Assemblies

Occasionally you may require to access internal classes plus their members found in six assembly from code in a separate assembly. The 'internal' modifier prevents this type of access. This restriction can be circumvented using C# 2.0 friend assemblies.

The Internal Modifier

Sometimes you may wish to remove this restriction, allowing the internal classes and members in two assembly to be visible to other, specific assemblies. You may need to do this to split a huge assembly into several more manageable parts or to permit testing of internal items from a separate automated testing assembly. This can be achieved using friend assemblies.

The 'internal' access changer can be applied to classes and their members to restrict their visibility to external objects. Internal items are available outside of the class but only to other items within the same assembly. Classes in other assemblies are generally unaware of the internal elements.

Example:

In this example, the assembly makes internal types and internal members visible to the assembly called cs_friend_assemblies_2.

// cs_friend_assemblies.cs
// compile with: /target:library
using System.Runtime.CompilerServices;
using System;

[assembly:InternalsVisibleTo("cs_friend_assemblies_2")]

// internal by default
class Class1
{
    public void Test()
    {
        Console.WriteLine("Class1.Test");
    }
}

// public type with internal member
public class Class2
{
    internal void Test()
    {
        Console.WriteLine("Class2.Test");
    }
}

If this assembly gives another assembly (assembly C) access to its internal types and members, assembly C does not automatically become a friend of assembly cs_friend_assemblies.dll.

// cs_friend_assemblies_2.cs
// compile with: /reference:cs_friend_assemblies.dll /out:cs_friend_assemblies_2.exe
public class M
{
    static void Main()
    {
        // access an internal type
        Class1 a = new Class1();
        a.Test();

        Class2 b = new Class2();
        // access an internal member of a public type
        b.Test();
    }
}

0 comments:

Post a Comment

Sponsored Ad

Website Update

Followers