2

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

rsp
  • 537
  • 2
  • 13
  • 1
    Does this answer your question? [What does the first arrow operator in this Func mean?](https://stackoverflow.com/questions/58597957/what-does-the-first-arrow-operator-in-this-funct-treturn-mean) – madreflection Jun 30 '20 at 15:09
  • I also gave an example in an answer. But yes, probably a duplicate of the above mentioned comment. – Nikolai Jun 30 '20 at 15:14

1 Answers1

4

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://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/statements-expressions-operators/expression-bodied-members

Nikolai
  • 555
  • 7
  • 17