Ali Kazmi
Ali Kazmi

Reputation: 3660

Are Method Attributes Inherited in C#?

Are attributes applied to an abstract method in a base class applied to the overridden versions in the child classes?

I hope the question is clear enough without an example.

Upvotes: 34

Views: 9715

Answers (3)

this. __curious_geek
this. __curious_geek

Reputation: 43217

It depends on the Attribute.

attributes applied to Attribute class defination, carry a property [AttributeUsageAttribute.Inherited] that determines if an attributed is inherited in the derived classes.

check out this sample

[global::System.AttributeUsage(AttributeTargets.Method, Inherited = true, 
     AllowMultiple = false)]
public sealed class MyAttribute : Attribute
{

    public MyAttribute (string FieldName)
    {
        //constructor.
    }

}

Upvotes: 17

Christian C. Salvadó
Christian C. Salvadó

Reputation: 827992

You can specify that by applying the AttributeUsage attribute to your custom ones, and setting the Inherited property (which is true by default). This property indicates if your attribute can be inherited by classes that are derived from the classes that have your custom attribute applied.

[AttributeUsage( Inherited = false)]
public class CustomAttribute : Attribute
{
}

Recommended read:

Upvotes: 9

Pavel Minaev
Pavel Minaev

Reputation: 101665

It depends on how the attribute itself is declared - see AttributeUsageAttribute.Inherited property.

Upvotes: 35

Related Questions