[Previous] [Contents] [Next]

Single-Use and Multiuse Attributes


You can use AttributeUsage to define attributes as either single-use or multiuse. This decision pertains to how many times a single attribute can be used on a single field. By default, all attributes are single-use, meaning that compiling the following results in a compiler error: -

using System;
using System.Reflection;

public class SingleUseAttribute : Attribute
{
    public SingleUseAttribute(String str)
    {
    }
}

// ERROR: This results in a "duplicate attribute" compiler error.
[SingleUse("abc")]
[SingleUse("def")]
class MyClass
{
}

class SingleUseApp
{
    public static void Main()
    {
    }
}

To fix this problem, specify on the AttributeUsage line that you want to allow the attribute to be attached multiple times to a given type. This would work: -

using System;
using System.Reflection;

[AttributeUsage(AttributeTargets.All, AllowMultiple=true)]
public class SingleUseAttribute : Attribute
{
    public SingleUseAttribute(String str)
    {
    }
}

[SingleUse("abc")]
[SingleUse("def")]
class MyClass
{

}

class MultiUseApp
{
    public static void Main()
    {
    }
}

A practical example of where you might want to use this approach is with the RegistryKeyAttribute attribute discussed in "Defining Attributes." Because it's conceivable that a field might be saved in multiple places in the Registry, you would attach the AttributeUsage attribute with the AllowMultiple named parameter as in the code here.

[Previous] [Contents] [Next]