skip to Main Content

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?

2

Answers


  1. In the first line app.UseEndpoints(endpoint => endpoint.MapControllers());, there is no curly braces, which means it’s a single statement lambda expression. It directly calls the MapControllers method on the endpoint parameter.

    In the second line app.UseEndpoints(endpoints => { endpoints.MapControllers(); });, curly braces are used to define a block of code. It allows you to include multiple statements if needed.

    As for why MapControllers is called twice, it seems to be redundant in this context. Both lines of code are functionally equivalent and achieve the same outcome of mapping the controllers to endpoints.

    Login or Signup to reply.
  2. 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(); 
    });
    

    Declaring MapController once is enough, not sure why it is written twice, you can remove one of them and make the changes accordingly to lamda expressions.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search