#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

About Sean
Software developer in the Twin Cities area, passionate about software development and sailing.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: