2

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.

aepot
  • 4,558
  • 2
  • 12
  • 24
  • 2
    For 2. see https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/statements-expressions-operators/expression-bodied-members . TL;DR it's syntactic sugar when you only have one statement in your method block. – Chronicle Nov 25 '20 at 15:52
  • 2
    For 1. it allows you to make your Main method async so you can use await. – Chronicle Nov 25 '20 at 15:53
  • @Chronicle The method is neither `async` nor does it use `await`. – Servy Nov 25 '20 at 16:02
  • @Chronicle Expression bodied members must be implemented with an expression, not a statement, hence the name *expression* bodied members. – Servy Nov 25 '20 at 16:02

1 Answers1

2

Explanations for both:

  1. Look at the c# 7.1 specification: https://learn.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://learn.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://learn.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

Thiago Cordeiro
  • 105
  • 1
  • 5
Athanasios Kataras
  • 25,191
  • 4
  • 32
  • 61