Home > Net >  Meaning of extending a class with " : base(typeof(classname))" (C#)
Meaning of extending a class with " : base(typeof(classname))" (C#)

Time:05-02

I have read this

https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/base.

but I still don't understand what this line means.

public CustomAuthorizeAttribute(string role) : base(typeof(CustomAuthorize))

CustomAuthorize is a class that extends IAuthorizationFilter.

what does base(typeof(CustomAuthorize)) mean?

Is it trying to call the constructor of the IAuthorizationFilter? why is it using typeof ?

The full class is:

public class CustomAuthorizeAttribute : TypeFilterAttribute
 {
        public CustomAuthorizeAttribute(string role) : base(typeof(CustomAuthorize))
       {
            Arguments = new object[] { role };
       }
 }

public class CustomAuthorize : IAuthorizationFilter
    {
        private readonly string role;

        public CustomAuthorize(string role)
        {
            this.role = role;
        }

        public void OnAuthorization(AuthorizationFilterContext context)
        {
         Some code

CodePudding user response:

base(...) is used to call a member of your base class. In this case, it seems like you are calling the constructor of the class you inherit from.

typeof(...) returns the Type of a defined type.

To sum it up, the command

public CustomAuthorizeAttribute(string role) : base(typeof(CustomAuthorize))

calls the constructor of the class, CustomAuthorizeAttribute inherits from by passing the parameter typeof(CustomAuthorize). This passed type then may be used to instanciate it for usage later on in the base class.

  • Related