Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Attribute inheritance not working as I would expect

I have a property in a base class with some attributes on it:

[MyAttribute1]
[MyAttribute2]
public virtual int Count
{
  get
  {
    // some logic here
  }
  set
  {
    // some logic here
  }
}

In a deriving class I have done this, because I want to add MyAttribute3 to the property and I cannot edit the base class:

[MyAttribute3]
public override int Count
{
  get
  {
     return base.Count;
  }
  set
  {
     base.Count = value;
  }

}

However, the property is now behaving like it doesn't have MyAttribute1 and MyAttribute2 on it. Am I doing something wrong, or do attributes not inherit?

like image 356
Fiona - myaccessible.website Avatar asked Dec 16 '22 23:12

Fiona - myaccessible.website


2 Answers

Attributes are not inherited by default. You can specify this using the AttributeUsage attribute:

[AttributeUsage(AttributeTargets.Property, Inherited = true)]
public class MyAttribute : Attribute
{
}
like image 106
Lee Avatar answered Dec 28 '22 11:12

Lee


It appears to work fine for me, if you're just using the method .GetType().GetCustomAttributes(true) this doesn't acually return any attributes, even if you set Inherited=true.

[AttributeUsage(AttributeTargets.Property, Inherited = true, AllowMultiple = true)]
sealed class MyAttribute : Attribute
{
    public MyAttribute()
    {
    }
}

[AttributeUsage(AttributeTargets.Property, Inherited = true, AllowMultiple = true)]
sealed class MyAttribute1 : Attribute
{
    public MyAttribute1()
    {
    }
}

class Class1
{
    [MyAttribute()]
    public virtual string test { get; set; }
}

class Class2 : Class1
{
    [MyAttribute1()]
    public override string test
    {
        get { return base.test; }
        set { base.test = value; }
    }
}

Then get the custom attributes from class 2.

Class2 a = new Class2();

MemberInfo memberInfo = typeof(Class2).GetMember("test")[0];
object[] attributes = Attribute.GetCustomAttributes(memberInfo, true);

attributes shows 2 elements in the array.

like image 21
Andy Avatar answered Dec 28 '22 10:12

Andy