views:

202

answers:

4

Hello. I am learning about Attributes and I still didn't understand what the Inherited bool property refers to. Does it mean that If i define my classe AbcAtribute, if I inherit another class from it, that derived class will also have that same attribute applied to it?

Thanks

+2  A: 

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().First());
ShuggyCoUk
A: 

Well, now that I think of it, I am not sure I made the question I really had. Let's imagine the following:

[Random]
class Mother {
}

class Child : Mother {
}

Does Child also have Random attribute applied to it?

devoured elysium
Yes it does. -and I need more characters :)-
apocalypse9
@devoured elysium: This should be an edit to your above question, rather than an answer. Makes the 'conversation' of the page more cohesive, less scattered.
Joel B Fant
A: 

That is what it means...

More info here: http://www.csharphelp.com/archives2/archive389.html

apocalypse9
Sorry for the duplication- Three people answered while I was posting.
apocalypse9
+2  A: 

When Inherited = true 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.

cmdematos.com