#473 – Specifying what Type of Elements a Custom Attribute Can Be Applied To

When you define a custom attribute, you can attach it to a variety of program elements by default.  But if your attribute is meant to apply to only one (or more) elements, you can specify that when you define the attribute.

You define which elements your custom attributes can be attached to by specifying the AttributeUsage attribute along with the definition of your attribute.  You specify one or more AttributeTargets values.  (Intellisense will provide a list, as shown below).

In the example below, I’ve specified that the PopCulture attribute may be used on parameters, properties and fields.

    [AttributeUsage(AttributeTargets.Parameter | AttributeTargets.Property | AttributeTargets.Field)]
    public sealed class PopCultureAttribute : Attribute
    {

If we try attaching the attribute to an unsupported element, like a method, we get an error at compile time.

Advertisement