Search code examples
c#attributesvirtual

Shall the attribute properties be virtual?


At MSDN an example to write a custom attribute shows the following strange behavior

[AttributeUsage(AttributeTargets.All)]
public class MyAttribute : Attribute
{ 
  public virtual string Name
  {
    get {return name;}
  }

  // Define Level property. 
  // This is a read-only attribute. 

  public virtual string Level
  {
    get {return level;}
  }

  // Define Reviewed property. 
  // This is a read/write attribute. 

  public virtual bool Reviewed
  {
    get {return reviewed;}
    set {reviewed = value;}
  }
}

Why all properties are virtual?


Solution

  • There's section on the particular MSDN article that the OP mentioned that is about attribute "inheritance", i.e. if you have a class with a method that is virtual and is annotated with an attribute, and you add a subclass and override that method, will the subclass method have the attribute applied to it? That's what [AttributeUsage(AttributeTargets.Method, Inherited = false)] is about in the Inherited Property section.

    Specifically:

    public class MyClass
    {
        [MyAttribute]
        [YourAttribute]
        public virtual void MyMethod()
        {
            //...
        }
    }
    

    Where YourAttribute is configured with AttributeUsage(AttributeTargets.Method, Inherited = false)] and MyAttribute has the default configuration.

    public class MyClass
    {
        [MyAttribute]
        [YourAttribute]
        public virtual void MyMethod()
        {
            //...
        }
    }
    
    public class YourClass : MyClass
    {
        // MyMethod will have MyAttribute but not YourAttribute. 
        public override void MyMethod()
        {
            //...
        }
    
    }
    

    The default value for Inherited is true.

    So in short, those properties are virtual in the article to describe this feature.