#1,024 – Exposing internal Members to Another Assembly

Internal class members are accessible within the class in which they are defined, as well as from other code within the same assembly.

Suppose that we define an internal field as follows:

    public class Dog
        internal static int DogCount = 0;

        public string Name;

        public Dog(string name)
            Name = name;

Code within another assembly that is using the Dog class will not be able to access the DogCount property.

It’s sometimes useful, however, to make internal members accessible to testing code that exists in another assembly.  We can do this with the InternalsVisibleTo attribute.  In the example above, we can define the following within AssemblyInfo.cs in the library containing the Dog class.

[assembly: InternalsVisibleTo("DogTester")]

Code within the DogTester assembly can now access internal members in Dog.

            Dog d = new Dog("Kirby");
            Dog d2 = new Dog("Jack");

            Console.WriteLine("We've created {0} dogs", Dog.DogCount);