Saturday, January 3, 2009

InternalsVisibleTo Attribute Usage

Before going into detail of InternalsVisibalTo attribute usage i would like to clear two access modifier in C#.

Internal : Access limited to current assembly.

Protected Internal : This means that protected or internal. So access limited to all class of current assembly or in other assembly class derive from this class.

In certain situation that is needed when you write your own set of classlibrary that you have to access internal of other assembly.In that case this attribute is usefull.

InternalsVisibalTo attribute applied at assembly level.

For example you have Two Assembly.

One in Library1 and Another one is Library2.

Library1 Contains Following Code.

public class Library1Class
    {
        protected internal void TestProctectedInternal()
        {
            Console.WriteLine("You are in protected internal method");
        }

        internal void TestInternal()
        {
            Console.WriteLine("You are in internal method");
        }    

         public void TestPublic()
        {
            Console.WriteLine("You are in public method");
        }

    }

Build Library1. That create library1.dll .

Now In Library2 you want to use Library1. So you add reference of Library1.

Library2 sample Code.

public class Library2Class
    {
        public void TestMethod()
        {
            Library1.Library1Class cls = new InterVisibalsToTest.Class1(); 

           cls.TestPublic(); // it’s ok

           cls.TestInternal(); // can’t access due to protection level.

           cls.TestProtectedInternal(); // can’t access due to protection level.                      
        }
    }

When you compile Library2 you can see two errors in build. (Mark as red in above code).

Now in order to avoid this error and give access to Library2 so it can access Internal and Protected Internal member, you have to use InternalsVisibleTo attribute in Library1 assemblyinfo.cs.

You have to add following line in assemlbyinfo.cs

[assembly: InternalsVisibleTo("Library2")]

After apply this attribute again build library1 and update reference in Library2. Now you have access of both method . TestInternal() and TestProtectedInternal();

Also possible to grant access to more than one assembly. For that you just have to add another line in assemlbyinfo.cs with diffrent assembly name.

For Example :

[assembly: InternalsVisibleTo("Library2")]                     [assembly: InternalsVisibleTo("Library3")].

Please give your comment on this.

1 comment:

Anonymous said...

hi,
great information

post this type of solutions in http://ranksheet.com/solutions you will get Specialist certificate.

some of my solutions http://ranksheet.com/Solutions/Search/Default.aspx?by=author&code=krish