How does inheritance work for Attributes?

When Inherited = true (which is the default) it means that the attribute you are creating can be inherited by sub-classes of the class decorated by the attribute.

So – if you create MyUberAttribute with [AttributeUsage (Inherited = true)]

[AttributeUsage (Inherited = True)]
MyUberAttribute : Attribute
{
   string _SpecialName;
   public string SpecialName
   { 
     get { return _SpecialName; }
     set { _SpecialName = value; }
   }
}

Then use the Attribute by decorating a super-class…

[MyUberAttribute(SpecialName = "Bob")]
class MySuperClass 
{
  public void DoInterestingStuf () { ... }
}

If we create an sub-class of MySuperClass it will have this attribute…

class MySubClass : MySuperClass
{
   ...
}

Then instantiate an instance of MySubClass…

MySubClass MySubClassInstance = new MySubClass();

Then test to see if it has the attribute…

MySubClassInstance <— now has the MyUberAttribute with “Bob” as the SpecialName value.

Leave a Comment