Search code examples
c#asp.netlambdamiddlewarecurly-braces

What is the difference in C# lambda when the curly braces are used and when not?


What is the difference in C# lambda when the curly braces are used and when not?

I am working on a project and we have the following piece of code:

public void Configure(IApplicationBuilder app)
{
    ... //some other code goes here
    app.UseEndpoints(endpoint => endpoint.MapControllers());

    app.UseEndpoints(endpoints => { endpoints.MapControllers(); });
}

Is there any difference between the { endpoints.MapControllers(); } and the endpoint.MapControllers()? Why would the MapControllers be called twice?


Solution

  • In the first case where there is no curly braces it will return the value of evaluated expression

    app.UseEndpoints(endpoint => endpoint.MapControllers());
    

    In the second case where there is curly braces it will allow you to add multiple statements, and at the end you need to call return statement explicitly to get the evaluated value.

    app.UseEndpoints(endpoints => 
    { 
       other statements ...
       return endpoints.MapControllers(); 
    });