How to control the usage of an Attribute in C#

What is AttributeUsage

The AttributeUsage attribute specifies the types of items to which an attribute can be applied. AttributeUsage is another name for the System.AttributeUsageAttribute class.

AttributeUsage has the following constructor:

AttributeUsage(AttributeTargets item)

item specifies the item or items upon which the attribute can be used.

AttributeTargets is an enumeration that defines the following values:

  • All
  • Assembly
  • Class
  • Constructor
  • Delegate
  • Enum
  • Event
  • Field
  • Interface
  • Method
  • Module
  • Parameter
  • Property
  • ReturnValue
  • Struct

Two or more of these values can be used together as follows.

AttributeTargets.Field | AttributeTargets.Property

AttributeUsage supports two named parameters: AllowMultiple and Inherited. AllowMultiple, a bool value. Whether the attribute can be applied more than one time to a single item. Inherited, a bool value. Whether the attribute is inherited by derived classes. The default setting for both AllowMultiple and Inherited is false.

Example

The following code marks the Attribute usage to all.


using System;//  w  w  w.  ja v a 2  s .co m

[AttributeUsage(AttributeTargets.All)] 
public class MyAttribute : Attribute { 
  string remark;
 
  public MyAttribute(string comment) { 
    remark = comment; 
  } 
 
  public string Remark { 
    get { 
      return remark; 
    } 
  } 
  public void Main(){}
} 

The code above generates the following result.





















Home »
  C# Tutorial »
    Custom Types »




C# Class
C# Struct
C# Interface
C# Inheritance
C# Namespace
C# Object
C# Delegate
C# Lambda
C# Event
C# Enum
C# Attribute
C# Generics
C# Preprocessor