#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;
            DogCount++;
        }
    }

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);
Advertisements

About Sean
Software developer in the Twin Cities area, passionate about .NET technologies. Equally passionate about my own personal projects related to family history and preservation of family stories and photos.

One Response to #1,024 – Exposing internal Members to Another Assembly

  1. Pingback: iOS 8 and iWatch - The Daily Six Pack: February 4, 2014

Leave a Reply

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

WordPress.com Logo

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

Twitter picture

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

Facebook photo

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

Google+ photo

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

Connecting to %s

%d bloggers like this: