Home > database >  how C# differentiates different delegate signature?
how C# differentiates different delegate signature?

Time:01-08

the UseExtensions has two methods

public static class UseExtensions {

   // method1
   public static IApplicationBuilder Use(this IApplicationBuilder app, Func<HttpContext, RequestDelegate, Task> middleware) {
      ...
   }
   
   // method2
   public static IApplicationBuilder Use(this IApplicationBuilder app, Func<HttpContext, Func<Task>, Task> middleware) {
      ...
   }
}

so when we write:

app.Use(async (context, next) => {
   await context.Response.WriteAsync("Hello World");
   await next();
});

it always calls method2, how can I rewrite the above method so that method1 is picked by the compiler?

CodePudding user response:

Specify the type of the arguments in the lambda

app.Use(async (HttpContext context, RequestDelegate next) => ...

Just because we don't usually specify then doesn't mean we aren't allowed to, and specifying them in a case like this allows the compiler to make a different judgement about "which one of these two similar things is a better match for..."

  •  Tags:  
  • Related