0

If internal class can only be accessed by anywhere in same assembly and it can't be accessed outside the assembly how Main() method is called by CLR?

using System;

namespace  test
{
     internal class Program {
        public static void Main(String[] args){
            Console.WriteLine("Testing Internal Modifier!!");
            Console.ReadLine();
        }
    }

}

Thanks.

arjun kr
  • 823
  • 1
  • 8
  • 22
  • 1
    They are marked by the compiler as 'entrypoint'. The CLR can just do "whatever it wants", within bounds. (http://www.ecma-international.org/publications/files/ECMA-ST/ECMA-335.pdf - II.15.4.1.2, page 181) – Caramiriel Aug 03 '18 at 11:36
  • 1
    This is clearly a special, since CLR is not bound by the same rules when it executes the code I assume – Ilya Chernomordik Aug 03 '18 at 11:36
  • Anything can be accessed anywhere via reflection and other methods, but in standard code it would be inaccessible – Blue Aug 03 '18 at 11:37
  • 1
    The CLR isn't written in C# and is not bound by the rules of C#, or even the rules of .NET (except insofar as it has to make programs run with the expected semantics in order to be useful). If it was Judge Dredd, it would be shouting "I *am* the law". – Jeroen Mostert Aug 03 '18 at 11:45
  • 1
    It is the C# compiler that sets the assembly's entrypoint, the CLR just calls it and doesn't care how it is declared and what it does. It is the C# compiler that complains when you forget to write Main() or have more than one. It is also the one that *could* complain when it isn't public. But they decided not to. For a pretty good reason, arguably it *should* be private because nothing good can happen when other code also calls Main(). – Hans Passant Aug 03 '18 at 12:30

1 Answers1

2

Private, protected, internal etc. modifiers are there to keep your code clean and help you make less errors. Other than that, everything is still callable, those modifiers are in no way a security tool to prevent the CLR or even other code from calling your code.

Using reflection you can call every single method in your class, be it private, internal or public. You can even declare Main() as private, it'll still be the entry point to your application.

Markus Dresch
  • 5,290
  • 3
  • 20
  • 40