#20 – C# Main Method

The Main method is the entry point of a C# application. When the application is started, the Main method is the first method that is invoked.

There can only be one entry point in a C# program. If you have more than one class that has a Main method, you must compile your program with the StartupObject compiler option to specify which Main method to use as the entry point.

Starting in C# 9, you don’t have to explicitly include a Main method in a console application project.
Instead, you can use the top-level statements feature to minimize the code you have to write. In this case, the compiler generates a class and Main method entry point for the application.

The following is a list of valid Main signatures:

public static void Main() { }
public static int Main() { }
public static void Main(string[] args) { }
public static int Main(string[] args) { }
public static async Task Main() { }
public static async Task<int> Main() { }
public static async Task Main(string[] args) { }
public static async Task<int> Main(string[] args) { }

Code Sample:

using System;
using System.Threading.Tasks;

class Program
{
    static async Task<int> Main(string[] args)
    {
        return await AsyncTestMethod();
    }

    private static async Task<int> AsyncTestMethod()
    {
        Console.WriteLine("Hello async Main method.");

        return 0;
    }
}

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.