-1

I am little bit confused.

I know that public is accessible from anywhere and internal classes are accessible only within the assembly.

But I found something strange in my code.

I've got three projects in one solution. All projects shares the same namespace.

Project A (main executable)

namespace Everything 
{
   class Program 
   {
      void Main() 
      {
         Runner r = new();
      }
   }
}

Project B (library class)

namespace Everything 
{
   public class Runner 
   {
      public Runner() 
      {
         // Loads external assembly in runtime and creates instance
         Assembly assembly = Assembly.Load("my.dll","my.pdb");
         Type type = assembly.GetType("Everything.InternalClass");
         Execute Instance = (Execute)Activator.CreateInstance(type);
      }
   }

   public class Execute
   {
       //something to do
   }
}

And finally Project C (my.dll) (another class library)

namespace Everything 
{
   class InternalClass : Execute
   {
      // This is executed in correct way - even it is in different assembly and it is set as internal (by default)
   }
}

Why this is working properly? I was thinking, that I need to use public in my Project C - becuase it is in different assembly...

Josef Širůčka
  • 303
  • 1
  • 2
  • 9

2 Answers2

2

Accessibility modifiers affect where types and members are visible from normal C# code. Reflection allows you to bypass all that. You can also set private fields via reflection and more.

If you want a normal C# way to access internal types, you can use the InternalsVisibleTo attribute.

Joey
  • 344,408
  • 85
  • 689
  • 683
1

The GetType returns everything you search for. If you want to get the public members, use GetExportedTypes instead. With reflection you can see and use all members.

alexrait
  • 407
  • 3
  • 15