Faloude Faloude - 5 months ago 30
C# Question

C# class works without initialisation (or call)

I just started learning C# (on Xamarin) and I'm confused about something, coming from a PHP background.

I used a fresh console project template and there is a class in Program.cs

using System;

namespace Test
class MainClass
public static void Main(string[] args)
Console.WriteLine("Hello World!");

This writes Hello World! to the console as expected. But the class
has never been initialized. Why is it executed?


Changing my question: Who executed the constructor?


Main is the entry point of the program. The operating system calls the Main method for you when you run the program. Because Main is a static method, it does not need to create an instance of MainClass to do so.

To be a valid entry point, the Main method must be static and have return type void or int, and either no parameters or a single string[] parameter. (See: https://msdn.microsoft.com/en-us/library/acy3edy3.aspx)

If you have multiple Main methods in your program that are valid entry points, you choose which one to use with compiler settings.