C# class without main method

后端 未结 10 616
情话喂你
情话喂你 2021-01-02 02:44

I\'m learning C# and I\'m very new to it, so forgive me for the seemingly stupid question. I have some experience in Java, and I noticed that C# programs also need a m

10条回答
  •  感动是毒
    2021-01-02 03:09

    Main is required, but C#9 coming up with feature such that you you will not write Main but it will act as Main.

    In C# 9.0 you can just choose to write your main program at the top level instead:

    using System;
    
    Console.WriteLine("Hello World!");
    

    Any statement is allowed. The program has to occur after the usings and before any type or namespace declarations in the file, and you can only do this in one file, just as you can have only one Main method today.

    If you want to return a status code you can do that. If you want to await things you can do that. And if you want to access command line arguments, args is available as a “magic” parameter.

    Local functions are a form of statement and are also allowed in the top level program. It is an error to call them from anywhere outside of the top level statement section.

    Reference: https://devblogs.microsoft.com/dotnet/welcome-to-c-9-0/#top-level-programs

提交回复
热议问题