Sunday, September 27, 2009

internal - A keyword in C#


internal” is a new access modifier for types and type members, in addition to the existing private, public and protected. Internal types or members are accessible only within files in the same assembly. When “protected internal” is used, it keeps access limited to the current assembly or types derived from the containing class.

public class BaseClass
{
    // Only accessible within the same assembly
    internal static int count = 0;
}

A common use of internal access is in component-based development because it enables a group of components to cooperate in a private manner without being exposed to the rest of the application code.
E.g. a framework for building graphical user interfaces could provide Control and Form classes that co-operate using members with internal access. Since these members are internal, they are not exposed to code that is using the framework.

It is an error to reference a member with internal access outside the assembly within which it was defined.

Assembly1.cs
// Compile with: /target:library
internal class BaseClass
{
   public static int nCount = 0;
}

// Assembly2.cs
// Compile with: /reference:Assembly1.dll
class TestAccess
{
   static void Main()
   {
      BaseClass myBase = new BaseClass();       // Error: CS0122; 'member' is inaccessible
// due to its protection level
   }
}

No comments: