131

What does the Inherited bool property on attributes refers to?

Does it mean that if I define my class with an attribute AbcAtribute (that has Inherited = true), and if I inherit another class from that class, that the derived class will also have that same attribute applied to it?

To clarify this question with a code example, imagine the following:

[AttributeUsage(AttributeTargets.Class, Inherited = true)]
public class Random: Attribute
{ /* attribute logic here */ }

[Random]
class Mother 
{ }

class Child : Mother 
{ }

Does Child also have the Random attribute applied to it?

MrLore
  • 3,759
  • 2
  • 28
  • 36
devoured elysium
  • 101,373
  • 131
  • 340
  • 557
  • 4
    It was not the case when you asked the question, but today the [official documentation of the `Inherited` property](https://msdn.microsoft.com/en-us/library/system.attributeusageattribute.inherited.aspx) has an elaborate example that shows the difference between `Inherited=true` and `Inherited=false` for both an inherited class and an `override` method. – Jeppe Stig Nielsen Aug 28 '17 at 20:31

3 Answers3

141

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.

Samuel Katz
  • 24,066
  • 8
  • 71
  • 57
cmdematos.com
  • 1,976
  • 1
  • 11
  • 9
18

Yes that is precisely what it means. Attribute

[AttributeUsage(Inherited=true)]
public class FooAttribute : System.Attribute
{
    private string name;

    public FooAttribute(string name)
    {
        this.name = name;
    }

    public override string ToString() { return this.name; }
}

[Foo("hello")]
public class BaseClass {}

public class SubClass : BaseClass {}

// outputs "hello"
Console.WriteLine(typeof(SubClass).GetCustomAttributes(true).First());
Nordic Mainframe
  • 28,058
  • 10
  • 66
  • 83
ShuggyCoUk
  • 36,004
  • 6
  • 77
  • 101
3

Attribute inheritance is enabled by default.

You can change this behavior by:

[AttributeUsage (Inherited = False)]
Kellen Stuart
  • 7,775
  • 7
  • 59
  • 82