On Tip #107 I explained what internal members are and how to define them. Let’s check today how to make internal types or internal members to be accessed from a known external assembly.
- Create a class library project and name it AssemblyA;
- Open the Class1.cs file and replace the existing code with the following code:
public class Foo
internal void M()
Console.WriteLine(“This is an internal method existing in the Foo class.”);
- Add a new class library project to the solution and name it AssemblyB;
- Right-click on the new project and add a reference to AssemblyA project;
- Open the Class1.cs file and from the class constructor create a new instance of Foo class;
Foo foo = new Foo();
- Resolve any import issue by adding an using statement to the AssemblyA on the top of the class;
- Try to access the M method from AssemblyA;
- Compile the code. You will get a compiler error because the method is not available. Since it’s defined as an internal method it is not available from outside;
- Back to the Foo class on the AssemblyA, add an import to System.Runtime.CompilerServices namespace;
- After the using statement added on the previous step, let’s add the InternalsVisibleTo attribute to define the AssemblyB as a friendly assembly that may access the internal member:
- Compile the code. Now you are able to access the internal member from an outside assembly.
To get more information about friend assemblies, click here!