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
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.
In the first case where there is no curly braces it will return the value of evaluated expression
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.
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.