c# Main() function in .net core console apps

Viewed 540

I'm just learning .NET Core and I'm trying to make sense of the way the Main() function is coded. When I see code examples of .NET core prorgrams, this is what I see:

static Task Main(string[] args) => 
    CreateHostBuilder(args).Build().Run();

My questions are:

  1. Why return a type of Task from the Main(), and how/where is a type of Task being instantiated? Is this something done in the background by the framework?

  2. Why use a lambda expression for the body of the Main() function? From all the documentation I've read about Lambda expressions, they are used either for delegates or expression trees. Neither of those are present here.

1 Answers

Explanations for both:

  1. Look at the c# 7.1 specification: https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/proposals/csharp-7.1/async-main

Allow await to be used in an application's Main / entrypoint method by allowing the entrypoint to return Task / Task and be marked async.

Example usage:


using System;
using System.Net.Http;

class Test
{
    static async Task Main(string[] args) =>
        Console.WriteLine(await new HttpClient().GetStringAsync(args[0]));
}

It's also worth pointing out that:

  • (1) If await isn't used inside Main(), it can return Task without being marked as async.
  • (2) When Main() returns Task, the compiler generates a new entry point

static Task Main() results in the compiler emitting the equivalent of private static void $GeneratedMain() => Main().GetAwaiter().GetResult(); (https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/main-and-command-args/main-return-values#compiler-generated-code).

  1. The lambda is an expression-bodied member. These are syntactic sugar for simpler expressions.

Expression body definitions let you provide a member's implementation in a very concise, readable form.

https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/statements-expressions-operators/expression-bodied-members

Example

public void DisplayName() => Console.WriteLine(ToString());

The difference with lamdas is here: Expression-bodied members vs Lambda expressions

Related