Search code examples
c#access-specifier

C# internal Access Specifiers,


I have Created one ConsoleApplication to understand Access Specifiers.

Below is my code for internal, I can access this class from outside the Assembly.

namespace Assembly_1 //This is first assembly.
{       
   public class Base
   {
       //internal class
       internal class B
       {
          public static void fnB()
          {
            Console.WriteLine("fnB");
          }
       }        
   }    
}

namespace Assembly_2 //This is second assembly.
{   
    public class Derived : Assembly_1.Base
    {            
        public class D
        {
            public void fnD()
            {
                B.fnB();//how can I access this class?
            }
        }
    }
}

And this is where I am Accessing it.

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {                
            Assembly_2.Derived.D d = new Assembly_2.Derived.D();
            d.fnD();
        }
    }
}

My Question

Right now I can Access Class B and it's methods like fnB() in Derived.

Everything works fine. but How?

How can I access the B Class outside Assembly_1?


Solution

  • As I worte in the comments:

    You are confusing the namespace and assembly terms. You can read about it here:(Assemblies and Namespace)

    Many namespaces can be defined in a single assembly.

    If you would like to check and understand the internal modifier, then you would have to create a new class library project (that will compile into a different assembly), define the Base class there and add a reference to it in your main console application. Then you will see that you don't have access to it anymore and the code will not compile.