Lambda expression in CreateHostBuilder in Web API project

Viewed 539

I have started learning C# and Web API recently. When I created a new ASP .NET Core Web Application in Visual Studio 2019, it generated some code for WeatherForecast. Following is code segment that I am having trouble understanding.

public class Program
{
    public static void Main(string[] args)
    {
        CreateHostBuilder(args).Build().Run();
    }

    public static IHostBuilder CreateHostBuilder(string[] args) =>
        Host.CreateDefaultBuilder(args)
            .ConfigureWebHostDefaults(webBuilder =>
            {
                webBuilder.UseStartup<Startup>();
            });
}

What is operator => doing here? CreateHostBuilder is a static method of class Program. And its definition should start with { and end with }. But after the closing braces of argument list, operator => is placed. I don't understand how this syntax works. Appreciate help in understanding this. Thanks

1 Answers

This is called expression-bodied.

public static IHostBuilder CreateHostBuilder(string[] args) =>
    Host.CreateDefaultBuilder(args)
        .ConfigureWebHostDefaults(webBuilder =>
        {
            webBuilder.UseStartup<Startup>();
        });

It's the same as:

public static IHostBuilder CreateHostBuilder(string[] args)
{
    return Host.CreateDefaultBuilder(args)
        .ConfigureWebHostDefaults(webBuilder =>
        {
            webBuilder.UseStartup<Startup>();
        });
}

Just a shortcut to a body with return. You can also use it for void functions with 1 line (and no return). Especially useful with properties:

private string name;
// new way:
public string Name { get => name; set => name = value; }
// old way:
public string Name { get { return name; } set { name = value; }

You can read more about it here: https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/statements-expressions-operators/expression-bodied-members

Related