But the class MainClass has never been initialised. Why is it executed
It doesn't need to be, as Main
is static
as others have pointed out.
When a managed assembly is compiled, there is section in it's header which tells .NET runtime where is the Main
method defined and is set as the Entry Point to the program. You can see it opening a managed .EXE is ILDASM:
TypeDef #3 (02000004)
-------------------------------------------------------
TypDefName: ConsoleApplication1.Program (02000004)
Flags : [NotPublic] [AutoLayout] [Class] [AnsiClass] [BeforeFieldInit] (00100000)
Extends : 01000010 [TypeRef] System.Object
Method #1 (0600000c) [ENTRYPOINT] <--- This
-------------------------------------------------------
MethodName: Main (0600000C)
Flags : [Private] [Static] [HideBySig] [ReuseSlot] (00000091)
RVA : 0x000021cc
ImplFlags : [IL] [Managed] (00000000)
CallCnvntn: [DEFAULT]
ReturnType: Void
1 Arguments
Argument #1: SZArray String
1 Parameters
(1) ParamToken : (0800000c) Name : args flags: [none] (00000000)
The runtime is the one in charge of invoking your Main
method.
If you really want to understand how the runtime is initialized, check out What happens when a .net application is started?