How to access internal class of one assembly to other assembly.
February 24, 2012 3 Comments
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
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
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 3d91c820e3cce1dbbbdf7428d97d4fc381ae4b9f9e3ecd36103bfa0d3d6754d5c46a9ed5ef0d2e2695b1a73eab31c8 d04cd2944a064592f1e985d6ec7ab18398265c4a7bcab758819ea87971426b37f2676a4d4383984e3b326d518f92be 9d2c9165a5421f2978d878629fef4492ce68bf8043f7dcdcd9692860d7103e2d0fe0c4235ffd7b83fdd8e450a7df6d 74bad5bf076721d77237d8935c41c5db250034b476d07a75588980680a681ad544ed881d6fabf42c031be550d99d55 3491230ebe5a5887c5ec47a5a148708b43769a0eb32248c08ebf9d414bae0fccdeaa4150203010001")]
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.