C# Internal

  • The internal keyword is one of access modifiers defined in C# for any types or their members.
  • The internal keyword makes the type or the member access only in the same assembly.
  • internal is the default access modifier when defining a class or a struct if the access modifier is not specified.
  • private instead of internal is the default access modifier for class members including fields or methods.
  • internal is always used in component development to make several components work together to realize some functionalities without being accessed directly from the outside applications.
  • internal and private hide the logics of the functions and make calling class invoke the methods it needs without knowing how they work.

Example 01-49-01

This example below was changed from the example 01-48-01 by removing "public" before the class Lib.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
using System;

namespace MyLib
{
    class Lib
    {
        public int plus(int a, int b)
        {
            return a + b;
        }

        public int minus(int a, int b)
        {
            return a - b;
        }
    }
}

In line 5, there is no access modifier any more. Then the default access modifier of the class Lib is internal, the class Lib can only be accessed in the assembly MyLib.dll. You will get a compile time error if you run the following example to access the class Lib.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
using System;
using MyLib;

namespace TestLib
{
    class Program
    {
        static void Main(string[] args)
        {
            Lib lib = new Lib();
            Console.WriteLine("a+b={0}", lib.plus(3, 5));
            Console.WriteLine("a-b={0}", lib.minus(3, 5));
            Console.Read();
        }
    }
}

In the above line 10, Lib is unavailable to the class Program because it can be seen only in the assembly MyLib.dll.

Now We'll change the MyLib library as follows.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
using System;

namespace MyLib
{
    public class Lib
    {
        int plus(int a, int b)
        {
            return a + b;
        }

        public int minus(int a, int b)
        {
            return a - b;
        }
    }
}

You can see we added "public" in line 5 to make the class accessed from outside code and removed the "public" in line 7 to test it in the Program class again. This time the class is instantiated in line 7 successfully but we still got a compile error because the default access modifier in plus method is private and cannot be accessed in another assembly TestLib.