I understand the source Asp.Net met the following construction

public class OAuthMiddleware<TOptions> : AuthenticationMiddleware<TOptions> where TOptions : OAuthOptions, new() { public OAuthMiddleware() { //code here... } } 

The OAuthMiddleware class inherits the AuthenticationMiddleware class and new() There are three questions.

  1. Is new() an anonymous class?
  2. Why in this anonymous class constructor OAuthMiddleware
  3. What is this design used for? What is the design pattern, if it is known that others are inherited from this class?

1 answer 1

Your OAuthMiddleware type is a generic type with a TOptions parameter, and the fact that after where is a constraint on this type-parameter of your generic type.

 where TOptions : OAuthOptions, new() 

means that the TOptions type must

  • be an OAuthOptions heir, and
  • have a public constructor without parameters.

What might the new() constraint be for? For example, in the class code you can create an instance of this type:

 TOptions opt = new TOptions(); 

Without restrictions on the existence of such a constructor, this code could not be compiled.

  • Clearly type (class) TOption does not initially exist, it is not a reserved word. Is creating a TOption class inheriting from an anonymous class and the OAuthOptions class? - Marat Batalandabad
  • one
    @MaratBatalandabad: No, it is not created, it is indicated . You cannot simply write OAuthMiddleware , you must always specify a parameter, for example: OAuthMiddleware<OAuthAuthorizationServerOptions> . Thus it is necessary that the type OAuthAuthorizationServerOptions (1) OAuthAuthorizationServerOptions , (2) Inherited from OAuthOptions , and (3) Had a constructor without parameters. There are no anonymous classes anywhere. - VladD