Override an inherited class attribute in a subclass

c#, custom-attributes

Solution

You could copy the BrowsableAttribute approach mentioned in one of the answers to the question you reference. You can make a constructor with a boolean that when set to `false` will denote that the attribute, although present, should not be handled. You can also add a parameterless constructor that set the property to `true`. This is the one that you will use most often unless you decide to override the attribute inherited from a base class.

[AttributeUsage(AttributeTargets.All, Inherited = true)]
public class MyAttributeAttribute : Attribute
{
    public bool Enabled { get; private set; }

    public MyAttributeAttribute()
        :this(true)
    {
    }

    public MyAttributeAttribute(bool enabled)
    {
        Enabled = enabled;
    }
}

Then when you reflect on your types and look for the attribute, you can check on the `Enabled` property and only if it is true you actually use it.

Your example class hierarchy will then be:

[MyAttribute]
public class ParentClass
[MyAttribute(false)]    
public class ChildClass; //Don't want MyAttribute

Problem

There's a fine question on overriding inherited attributes of properties. Suppose an attribute: ``` [AttributeUsage(AttributeTargets.All, Inherited = true)] public class MyAttributeAttribute : Attribute //... public class ParentClass { [MyAttribute] public String MyString; } public class ChildClass : ParentClass { new public String MyString; //Doesn't have MyAttribute } ``` But what if `MyAttribute` is set to a class? ``` [MyAttribute] public class ParentClass public class ChildClass; //Don't want MyAttribute ``` Is there a way to make ChildClass not inherit the attribute? Context: Purely theoretical. I want to make an attribute inheritable and want to know, if the case happens some day, if I can override it.

Original source

Related problems