Warm tip: This article is reproduced from stackoverflow.com, please click
asp.net asp.net-mvc c# intellisense

Why Does Named Parameter For A Custom Attribute Require `:` Syntax?

发布于 2020-03-27 10:27:11

I defined the following custom attribute:

[AttributeUsage(AttributeTargets.All)]
public class CustomAuthAttribute : AuthorizeAttribute
{
    private MyPermissionLevels requestedAccessLevel;

    public CustomAuthAttribute(object AccessLevel = null)
    {
        AccessLevel = AccessLevel ?? MyPermissionLevels.View;            
        if(AccessLevel.GetType() != typeof(MyPermissionLevels))
        {
            throw new ArgumentException("AccessLevel is invalid.");
        }
        this.requestedAccessLevel = (MyPermissionLevels)AccessLevel;
    }

        ... // Other Auth Stuff
}

When I apply this attribute to a controller as, for example, [CustomAuthAttribute (AccessLevel = MyPermissionLevels.Modify)] intellisense complains that:

The type or namespace name 'AccessLevel' could not be found. (etc?)

The potential fixes revealed by Alt + Enter include:

Change 'AccessLevel' to 'AccessLevel:'

Adding this colon (and by implication removing the = operator, which is not an automagical part of the suggested fix) does resolve the compilation error.

I am okay using a different syntax if that's all that need be. However, I would like to understand what I've done that prevents me from using the more common attribute field-initialization syntax as described in answers to Named parameters confusion and as can be done with the parent class:

[Authorize(Roles = "Modifiers")]

Questioner
Trevor Reid
Viewed
89
Amy 2019-07-03 23:11

The colon is necessary because that is the syntax for named parameters. The field isn't public, nor are you trying to assign to it. The field's name is requestedAccessLevel, not AccessLevel.

The parent class has a public property Roles, so in the line:

[Authorize(Roles = "Modifiers")]

Roles is not a named constructor parameter, it's a property, so named parameter syntax is not used. Indeed, that attribute doesn't have a constructor that accepts parameters. It only has public, assignable properties.