C# class without main method

后端 未结 10 524
情话喂你
情话喂你 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

    0 讨论(0)
  • 2021-01-02 03:13

    Try using /t:library switch with the compiler. By default it tries to make an .exe which, of course, needs an entry point (i.e. a main method). If you compile to a .dll you won't need that.

    But as HighCore suggested, if you are learning, just use Visual Studio (download one of the free versions if you haven't already) and let it worry about the compiler flags.

    0 讨论(0)
  • 2021-01-02 03:14

    Only one class with one method should be fine. If you want, you can set up the start up object in visual studio in the settings.

    0 讨论(0)
  • 2021-01-02 03:16

    If this is a console application, you need a Main method to start with. Otherwise (web application, for example), you don't need one.

    0 讨论(0)
提交回复
热议问题