How to access internal class of one assembly to other assembly.

It’s been long since I made a new Post. I was missing it a lot. But now I’ll be here with my normal way..
Today I am sharing a small but useful learning with you all..

As we all know,  Internal classes are visible in the same assembly.  And we make it internal based on our requirement. i e when we make a class internal, it means we don’t want that code written outside the assembly, able to access it.

Normally in our projects, we have a separate project for Unit Tests. And obviously we may require to test that internal class. There may be some other requirement where you may need to expose your internal classes to some assembly. But how to access the internal classes here.

There is a concept of Friend Assembly in C#. It allows us to access the internal classes in other assembly.
Note : Only Internal classes can be exposed to other assembly. Private classes can not be made available outside the assembly.

This can be applied at assembly level only. We need to apply InternalsVisibleToAttribute to assemblyinfo.cs.
This attribute is available in the namespace System.Runtime.CompilerServices . So first, Let’s see How it can be applied.

Say, I have a Project called Rules Engine and another project named TestProject. Now I want to use internal classes of RulesEngine in TestProject. I have a class ValidationRules in my RulesEngine project as

Internal Class

Now I want to use this class in my Test project. For that, obviously we need to first add the reference of RulesEngine. Then main part is in RulesEngine’s AssemblyInfo.cs add the line as

Note : AssemblyInfo.cs resides in the properties folder of the project

Here TestProject is the name of the assembly.

Now add the RulesEngine namesapce in you class and you can access the internal class as

As you can see, we made ValidationRules as Internal class but it shows that class in intellisense.

If the assembly has a strong name. Then you need to apply the attribute as

[assembly:InternalsVisibleTo("TestProject , PublicKey="3082010a0282010100bd3089fb4572a8536b9e894f0023c0bed41d3db1594038f373918226e69612005

Here other property of strong name like version culture must not be included.
One point must be noted , that either both assembly should be signed or both should be signed. You can not have one signed and another unsigned and vice versa.

Hope you all liked it.



3 thoughts on “How to access internal class of one assembly to other assembly.

  1. Pingback: Limiting the accessibilty – Another way of Friend Assemblies « Brij's arena of .NET

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s