-
Consider the following extension method: public static class ExtensionMethod
{
public static THttpContext WithAuthorizationHeader<THttpContext>(this THttpContext httpContext, string value)
where THttpContext : HttpContext
{
httpContext.Request.Headers.Add(HeaderNames.Authorization, value);
return httpContext;
}
} The following code happily compiles, as expected: var context = new DefaultHttpContext().WithAuthorizationHeader($"Bearer {token}"); But this code does not, even though I would expect it to: DefaultHttpContext context = new().WithAuthorizationHeader($"Bearer {token}"); // CS8754 "There is no target type for 'new()'" It appears the compiler is attempting to parse the entirety of the expression and infer the type from that, whereas to my mind it should be parsing and resolving I have checked https://docs.microsoft.com/dotnet/csharp/language-reference/proposals/csharp-9.0/target-typed-new but can't see anything that would imply this shouldn't work. |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 37 replies
-
Why would it do that? The compiler hasn't performed overload resolution yet, so it doesn't know that the type of the |
Beta Was this translation helpful? Give feedback.
-
In the miscellaneous section, it states it will not work: "It is disallowed when ... in a member access ( |
Beta Was this translation helpful? Give feedback.
Why would it do that? The compiler hasn't performed overload resolution yet, so it doesn't know that the type of the
new()
subexpression is going to be the same as the type of the whole expression. And without that, there is no connection betweennew()
andDefaultHttpContext
.