Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Default access modifier of Main() method

Tags:

c#

I create a sample class in vs2010.

Through Class View, I see the default access modifier for Main is internal.

I also see some people say that the default access modifier for Main is "implicitly private".

Visual Studio 2010 automatically defines a program’s Main() method as implicitly private. Doing so ensures other applications cannot directly invoke the entry point of another.

I know there are differences between internal and private. So which one is correct?

like image 942
q0987 Avatar asked Sep 17 '10 14:09

q0987


2 Answers

If your code appears like this:

static void Main()

then that's a private method. (The static part is orthogonal to accessibility, but is necessary to be an entry point.) In general, the default accessibility of any member is the most private accessibility that you could declare it. So for methods in a class or a struct, that's private. For top-level (non-nested) types it's internal. For any member declared in a class/struct, it's private1. For interface and enum members, it's public.

It's hard to understand exactly what you're seeing via Class View without seeing either your code or a screenshot of Class View, but the default accessibility for a method is definitely private. That's true regardless of whether it's the Main method or not.


1 Explicit interface implementation is a bit odd here, as it's neither private nor public; it's simply not accessible through the type, only through the interface.

like image 193
Jon Skeet Avatar answered Oct 07 '22 16:10

Jon Skeet


Although you tagged your question c#, let me say that the access modifiers for the default Program.Main generated by VS2010 actually depends on the project template, on these differ for each language. I quickly tried the following:

  • In a VB.NET console project, the Program module (static class) is Friend (i.e. internal in C#) and the Main static method is Public.

  • In a C# console project, Program is internal, and Main is private.

That is, a C# project will simply use the default access modifiers (internal for classes, private for methods).

like image 45
stakx - no longer contributing Avatar answered Oct 07 '22 16:10

stakx - no longer contributing