DCSIMG
August 2010 - Posts - David Birin's blog

August 2010 - Posts

Why can’t we be friends (Assemblies)?

This great song asks “why can’t we be friends?” well after working 5 years in .NET I found out that assemblies can be friends…

So what are friend assemblies, well it's pretty simple, it’s a way of giving another assembly access to the internal members on an assembly, and yes, it reminds me of C++ friend classes, but in C++ a friend has access to private members and in .NET only to internal members.

I created a new assembly in C# and I want other assemblies to access it internal members.

namespace Friendly
{
    internal class InternalClass
    {
        internal string internalString = "Howdy friend";
    }
}

Now all I need to do is to explicitly note the friends in the AssembleyInfo.cs file

[assembly: InternalsVisibleTo("SomeAssembly")]

Of course that in real life cases you would use a full assembly evidence with SN.

Now if you are working in C# just add a reference from “SomeAssembly” (the consumer) to the first assembly (the provider - above) and you can access the internal members.

static void Main(string[] args)
{
    Friendly.InternalClass ic = new Friendly.InternalClass();
    Console.WriteLine(ic.internalString);
}

But if you are working in C++/CLI (the language which replaced Managed C++) consuming a friend is a bit different, first of all don’t add a reference to the first assembly Visual studio, you need to include it manually in the following way, first of all add the path of the dll in the project setting under: VC++ Directories –> Reference Directories, now you need to add a special #using statement as seen bellow:

// FreindlyCLI.cpp : main project file.
 
#include "stdafx.h"
 
using namespace System;
#using "Friendly.dll" as_friend
 
int main(array<System::String ^> ^args)
{
    Friendly::InternalClass^ ic = gcnew Friendly::InternalClass();
    Console::WriteLine(ic->internalString);
    return 0;
}