Default access specifier of Main()

589 views Asked by At

What is the default access specifier of Main method in C#?

If the default access specifier of static void Main() is private, then how does an external entity eg. OS invoke this method?

Any foreign process should not be able to call this method.

3

There are 3 answers

0
Eric Lippert On BEST ANSWER

What is the default access specifier of Main method in C#?

The default access specifier of all methods is private.

Then how does an external entity such as the OS invoke this method?

It doesn't. The main method is invoked by the CLR. Since the CLR is the thing that is enforcing the semantics of privacy it can ignore it.

But that is not actually the right answer. The right answer is to say that your question reveals that you have a common but incorrect idea of what "private" applies to. "Private" does not mean "this method cannot be called from an external entity".

Rather, access modifiers apply to the name of the thing. That is, an access modifier determines the accessibility domain of the name of a thing: it determines the region of code in which the name could possibly mean the thing in question. The private modifier means "the accessibility domain of this entity is the entire body of the type in which it is declared". Any attempt to look up that name outside of that accessibility domain will not result in name resolution choosing the entity. Either name resolution will choose something else, or name resolution will fail.

It is absolutely possible to call a private method via some other mechanism. You can make a delegate to it and pass it around. You can use private reflection if you are sufficiently trusted. And so on. The invocation of the main method is just such a mechanism; it doesn't look up Main by name in the first place!

0
Max Truxa On

First, the OS knows nothing about your Main.

The CLR (which calls Main) can call it, no matter what access level you specified for it (internal, private, protected, public). You can even view and call/use all methods/types/interfaces from external libraries yourself using reflection (yes, internal and private, too).

0
Scott Yang On

Its default access specifier is private, although it also could be public or internal. from msdn: http://msdn.microsoft.com/zh-cn/library/acy3edy3 Further more, we wonder why the private method called by the external. I think that, access levels(public,internal,protected,private) defined in C# are just limited by compiler, it's a strict rule for IDE and developers, but to CLR and OS, they don't have to obey this rule, they can call any function or method from reflected address, like we could invoke method by reflecting, so the private Main method could be the entry.