Attribute Oriented Programming: Part 2

Here is Part 1

In this article we will have a deeper look into what we actually did in our first try at Attributes and also look at some of the features used.

When we created our first attribute we used a Attribute AttributeUsage on top of our attribute as shown below:

[AttributeUsage(AttributeTargets.All, AllowMultiple = false)]
    public sealed class FixMeAttribute : System.

Lets take a look at what it is.

AttributeUsage - Describes how a custom attribute class can be used.

Do read this

We had specified the AttributeTargets and AllowMultiple properties in our example.

In our example for the Property AttributeTargets we choose All. That would mean that the attribute we created could be applied to anything or everything. For Example: Assembly, Class, Constructor etc.

This is not exactly a bright thing to do as it would lead to runtime errors.

We could restrict our attribute to be used to Assembly or a class or Constructor as shown below:

Attribute Oriented Programming

Lets say we choose Enum option as shown below:

[AttributeUsage(AttributeTargets.Enum, AllowMultiple = false)]
public sealed class FixMeAttribute : System.Attribute

Now just run our program from first article again.

The Program does not build and throws a compile time error as:

Attribute Oriented Programming

Hence we can avoid many unwanted errors.

I will try to provide a example for each of the case in some future article.

Next AllowMultiple:

The AllowMultiple property indicates whether multiple instances of your attribute can exist on an element. If set to true, multiple instances are allowed; if set to false (the default), only one instance is allowed.

Lets test it with a scenario .

Modify the Attribute Usage as shown below :

  [AttributeUsage(AttributeTargets.All, AllowMultiple = false)]
    public sealed class FixMeAttribute : System.

Apply another FixMe attribute on the Class as shown below :

    [FixMe("Incorporate 4.0 features")]
    [FixMe("Incorporate 3.5 features")]
    class MyClass

Compile it. The following error is thrown.

Attribute Oriented Programming

Now lets modify the AllowMultiple = true as shown below:

[AttributeUsage(AttributeTargets.All, AllowMultiple = true)]
public sealed class FixMeAttribute : System.Attribute

Now when we run the Program. It Builds and the following output is displayed.

Attribute Oriented Programming

One last point I missed was in the CustomAttributeTest we used the following line as shown below:

Object[] atts = clazz.GetCustomAttributes(typeof(FixMeAttribute), false);

This statement was used to Access the FixMeAttribute at runtime.

Well we need not take the effort of passing the Type of the Attribute.

Simply used the code below and job would be done.

Object[] atts = clazz.GetCustomAttributes(false);

All the Types would be accessed.

In future article we will look into other usages of Attributes. Happy coding.