Attribute Class

[ This article is for Windows Phone 8 developers. If you’re developing for Windows 10, see the latest documentation. ]

Represents the base class for custom attributes.

Inheritance Hierarchy

System..::.Object
System..::.Attribute
More...

Namespace: System
Assembly: mscorlib (in mscorlib.dll)

Syntax

<AttributeUsageAttribute(AttributeTargets.All, Inherited := True, AllowMultiple := False)> _
Public MustInherit Class Attribute
[AttributeUsageAttribute(AttributeTargets.All, Inherited = true, AllowMultiple = false)]
public abstract class Attribute

The Attribute type exposes the following members.

Constructors

Name Description
Attribute Initializes a new instance of the Attribute class.

Top

Methods

Name Description
Equals Infrastructure. Returns a value that indicates whether this instance is equal to a specified object. (Overrides Object..::.Equals(Object).)
Finalize Allows an object to try to free resources and perform other cleanup operations before the Object is reclaimed by garbage collection. (Inherited from Object.)
GetCustomAttribute(Assembly, Type) Retrieves a custom attribute applied to a specified assembly. Parameters specify the assembly and the type of the custom attribute to search for.
GetCustomAttribute(MemberInfo, Type) Retrieves a custom attribute applied to a member of a type. Parameters specify the member, and the type of the custom attribute to search for.
GetCustomAttribute(Module, Type) Retrieves a custom attribute applied to a module. Parameters specify the module, and the type of the custom attribute to search for.
GetCustomAttribute(ParameterInfo, Type) Retrieves a custom attribute applied to a method parameter. Parameters specify the method parameter, and the type of the custom attribute to search for.
GetCustomAttribute(Assembly, Type, Boolean) Retrieves a custom attribute applied to an assembly. Parameters specify the assembly, the type of the custom attribute to search for, and an ignored search option.
GetCustomAttribute(MemberInfo, Type, Boolean) Retrieves a custom attribute applied to a member of a type. Parameters specify the member, the type of the custom attribute to search for, and whether to search ancestors of the member.
GetCustomAttribute(Module, Type, Boolean) Retrieves a custom attribute applied to a module. Parameters specify the module, the type of the custom attribute to search for, and an ignored search option.
GetCustomAttribute(ParameterInfo, Type, Boolean) Retrieves a custom attribute applied to a method parameter. Parameters specify the method parameter, the type of the custom attribute to search for, and whether to search ancestors of the method parameter.
GetCustomAttributes(Assembly) Retrieves an array of the custom attributes applied to an assembly. A parameter specifies the assembly.
GetCustomAttributes(MemberInfo) Retrieves an array of the custom attributes applied to a member of a type. A parameter specifies the member.
GetCustomAttributes(Module) Retrieves an array of the custom attributes applied to a module. A parameter specifies the module.
GetCustomAttributes(ParameterInfo) Retrieves an array of the custom attributes applied to a method parameter. A parameter specifies the method parameter.
GetCustomAttributes(Assembly, Boolean) Retrieves an array of the custom attributes applied to an assembly. Parameters specify the assembly, and an ignored search option.
GetCustomAttributes(Assembly, Type) Retrieves an array of the custom attributes applied to an assembly. Parameters specify the assembly, and the type of the custom attribute to search for.
GetCustomAttributes(MemberInfo, Boolean) Retrieves an array of the custom attributes applied to a member of a type. Parameters specify the member, the type of the custom attribute to search for, and whether to search ancestors of the member.
GetCustomAttributes(MemberInfo, Type) Retrieves an array of the custom attributes applied to a member of a type. Parameters specify the member, and the type of the custom attribute to search for.
GetCustomAttributes(Module, Boolean) Retrieves an array of the custom attributes applied to a module. Parameters specify the module, and an ignored search option.
GetCustomAttributes(Module, Type) Retrieves an array of the custom attributes applied to a module. Parameters specify the module, and the type of the custom attribute to search for.
GetCustomAttributes(ParameterInfo, Boolean) Retrieves an array of the custom attributes applied to a method parameter. Parameters specify the method parameter, and whether to search ancestors of the method parameter.
GetCustomAttributes(ParameterInfo, Type) Retrieves an array of the custom attributes applied to a method parameter. Parameters specify the method parameter, and the type of the custom attribute to search for.
GetCustomAttributes(Assembly, Type, Boolean) Retrieves an array of the custom attributes applied to an assembly. Parameters specify the assembly, the type of the custom attribute to search for, and an ignored search option.
GetCustomAttributes(MemberInfo, Type, Boolean) Retrieves an array of the custom attributes applied to a member of a type. Parameters specify the member, the type of the custom attribute to search for, and whether to search ancestors of the member.
GetCustomAttributes(Module, Type, Boolean) Retrieves an array of the custom attributes applied to a module. Parameters specify the module, the type of the custom attribute to search for, and an ignored search option.
GetCustomAttributes(ParameterInfo, Type, Boolean) Retrieves an array of the custom attributes applied to a method parameter. Parameters specify the method parameter, the type of the custom attribute to search for, and whether to search ancestors of the method parameter.
GetHashCode Returns the hash code for this instance. (Overrides Object..::.GetHashCode()()().)
GetType Gets the Type of the current instance. (Inherited from Object.)
IsDefined(Assembly, Type) Determines whether any custom attributes are applied to an assembly. Parameters specify the assembly, and the type of the custom attribute to search for.
IsDefined(MemberInfo, Type) Determines whether any custom attributes are applied to a member of a type. Parameters specify the member, and the type of the custom attribute to search for.
IsDefined(Module, Type) Determines whether any custom attributes of a specified type are applied to a module. Parameters specify the module, and the type of the custom attribute to search for.
IsDefined(ParameterInfo, Type) Determines whether any custom attributes are applied to a method parameter. Parameters specify the method parameter, and the type of the custom attribute to search for.
IsDefined(Assembly, Type, Boolean) Determines whether any custom attributes are applied to an assembly. Parameters specify the assembly, the type of the custom attribute to search for, and an ignored search option.
IsDefined(MemberInfo, Type, Boolean) Determines whether any custom attributes are applied to a member of a type. Parameters specify the member, the type of the custom attribute to search for, and whether to search ancestors of the member.
IsDefined(Module, Type, Boolean) Determines whether any custom attributes are applied to a module. Parameters specify the module, the type of the custom attribute to search for, and an ignored search option.
IsDefined(ParameterInfo, Type, Boolean) Determines whether any custom attributes are applied to a method parameter. Parameters specify the method parameter, the type of the custom attribute to search for, and whether to search ancestors of the method parameter.
Match When overridden in a derived class, returns a value that indicates whether this instance equals a specified object.
MemberwiseClone Creates a shallow copy of the current Object. (Inherited from Object.)
ToString Returns a string that represents the current object. (Inherited from Object.)

Top

Remarks

The Attribute class associates predefined system information or user-defined custom information with a target element. A target element can be an assembly, class, constructor, delegate, enum, event, field, interface, method, portable executable file module, parameter, property, return value, struct, or another attribute.

Information provided by an attribute is also known as metadata. Metadata can be examined at run time by your application to control how your program processes data, or before run time by external tools to control how your application itself is processed or maintained. For example, the .NET Framework predefines and uses attribute types to control run-time behavior, and some programming languages use attribute types to represent language features not directly supported by the .NET Framework common type system.

All attribute types derive directly or indirectly from the Attribute class. Attributes can be applied to any target element; multiple attributes can be applied to the same target element; and attributes can be inherited by an element derived from a target element. Use the AttributeTargets class to specify the target element to which the attribute is applied.

The Attribute class provides convenient methods to retrieve and test custom attributes.

Examples

The following code example demonstrates the usage of Attribute.

Imports System.Reflection

' An enumeration of animals. Start at 1 (0 = uninitialized).
Public Enum Animal
   ' Pets
   Dog = 1
   Cat
   Bird
End Enum

' Visual Basic requires the AttributeUsage be specified.
' A custom attribute to allow a target to have a pet.
<AttributeUsage(AttributeTargets.Method)> _
Public Class AnimalTypeAttribute
   Inherits Attribute

   ' The constructor is called when the attribute is set.
   Public Sub New(ByVal animal As Animal)
      Me.thePet = animal
   End Sub

   ' Keep a variable internally ...
   Protected thePet As Animal

   ' .. and show a copy to the outside world.
   Public Property Pet() As Animal
      Get
         Return thePet
      End Get
      Set(ByVal Value As Animal)
         thePet = Value
      End Set
   End Property
End Class

Class AnimalTypeTestClass
   <AnimalType(Animal.Dog)> _
   Public Sub DogMethod()
   End Sub

   <AnimalType(Animal.Cat)> _
   Public Sub CatMethod()
   End Sub

   <AnimalType(Animal.Bird)> _
   Public Sub BirdMethod()
   End Sub
End Class

Module Example
   Public Sub Demo(ByVal outputBlock As System.Windows.Controls.TextBlock)
      Dim testClass As New AnimalTypeTestClass()
      Dim tcType As Type = testClass.GetType()
      Dim mInfo As MethodInfo
      ' Iterate through all the methods of the class.
      For Each mInfo In tcType.GetMethods()
         Dim attr As Attribute
         ' Iterate through all the attributes of the method.
         For Each attr In Attribute.GetCustomAttributes(mInfo)
            If TypeOf attr Is AnimalTypeAttribute Then
               Dim attrCustom As AnimalTypeAttribute = _
                   CType(attr, AnimalTypeAttribute)
               outputBlock.Text += String.Format("Method {0} has a pet {1} attribute.", _
                    mInfo.Name(), attrCustom.Pet.ToString()) + vbCrLf
            End If
         Next
      Next
   End Sub
End Module

' Output:
' Method DogMethod has a pet Dog attribute.
' Method CatMethod has a pet Cat attribute.
' Method BirdMethod has a pet Bird attribute.
using System;
using System.Reflection;

// An enumeration of animals. Start at 1 (0 = uninitialized).
public enum Animal
{
   // Pets.
   Dog = 1,
   Cat,
   Bird,
}

// A custom attribute to allow a target to have a pet.
public class AnimalTypeAttribute : Attribute
{
   // The constructor is called when the attribute is set.
   public AnimalTypeAttribute(Animal pet)
   {
      thePet = pet;
   }

   // Keep a variable internally ...
   protected Animal thePet;

   // .. and show a copy to the outside world.
   public Animal Pet
   {
      get { return thePet; }
      set { thePet = Pet; }
   }
}

// A test class where each method has its own pet.
class AnimalTypeTestClass
{
   [AnimalType(Animal.Dog)]
   public void DogMethod() { }

   [AnimalType(Animal.Cat)]
   public void CatMethod() { }

   [AnimalType(Animal.Bird)]
   public void BirdMethod() { }
}

class Example
{
   public static void Demo(System.Windows.Controls.TextBlock outputBlock)
   {
      AnimalTypeTestClass testClass = new AnimalTypeTestClass();
      Type type = testClass.GetType();
      // Iterate through all the methods of the class.
      foreach (MethodInfo mInfo in type.GetMethods())
      {
         // Iterate through all the Attributes for each method.
         foreach (Attribute attr in
             Attribute.GetCustomAttributes(mInfo))
         {
            // Check for the AnimalType attribute.
            if (attr.GetType() == typeof(AnimalTypeAttribute))
               outputBlock.Text += String.Format(
                   "Method {0} has a pet {1} attribute.",
                   mInfo.Name, ((AnimalTypeAttribute)attr).Pet) + "\n";
         }

      }
   }
}
/*
 * Output:
 * Method DogMethod has a pet Dog attribute.
 * Method CatMethod has a pet Cat attribute.
 * Method BirdMethod has a pet Bird attribute.
 */

Version Information

Windows Phone OS

Supported in: 8.1, 8.0, 7.1, 7.0

Platforms

Windows Phone

Thread Safety

This type is thread safe.

See Also

Reference

System Namespace

Inheritance Hierarchy

System..::.Object
System..::.Attribute
Microsoft.Phone.Data.Linq.Mapping..::.IndexAttribute
System..::.AttributeUsageAttribute
System..::.CLSCompliantAttribute
System.CodeDom.Compiler..::.GeneratedCodeAttribute
System.ComponentModel..::.AlternateContentPropertyAttribute
System.ComponentModel..::.BrowsableAttribute
System.ComponentModel..::.CategoryAttribute
System.ComponentModel..::.DefaultValueAttribute
System.ComponentModel..::.DescriptionAttribute
System.ComponentModel..::.EditorBrowsableAttribute
System.ComponentModel..::.ReadOnlyAttribute
System.ComponentModel..::.TypeConverterAttribute
System..::.ContextStaticAttribute
System.Data.Linq.Mapping..::.DataAttribute
System.Data.Linq.Mapping..::.DatabaseAttribute
System.Data.Linq.Mapping..::.InheritanceMappingAttribute
System.Data.Linq.Mapping..::.TableAttribute
System.Diagnostics.CodeAnalysis..::.SuppressMessageAttribute
System.Diagnostics..::.ConditionalAttribute
System.Diagnostics.Contracts..::.ContractAbbreviatorAttribute
System.Diagnostics.Contracts..::.ContractArgumentValidatorAttribute
System.Diagnostics.Contracts..::.ContractClassAttribute
System.Diagnostics.Contracts..::.ContractClassForAttribute
System.Diagnostics.Contracts..::.ContractInvariantMethodAttribute
System.Diagnostics.Contracts..::.ContractOptionAttribute
System.Diagnostics.Contracts..::.ContractPublicPropertyNameAttribute
System.Diagnostics.Contracts..::.ContractReferenceAssemblyAttribute
System.Diagnostics.Contracts..::.ContractRuntimeIgnoredAttribute
System.Diagnostics.Contracts..::.ContractVerificationAttribute
System.Diagnostics.Contracts..::.PureAttribute
System.Diagnostics..::.DebuggableAttribute
System.Diagnostics..::.DebuggerBrowsableAttribute
System.Diagnostics..::.DebuggerDisplayAttribute
System.Diagnostics..::.DebuggerHiddenAttribute
System.Diagnostics..::.DebuggerNonUserCodeAttribute
System.Diagnostics..::.DebuggerStepThroughAttribute
System.Diagnostics..::.DebuggerTypeProxyAttribute
System..::.FlagsAttribute
System..::.MTAThreadAttribute
System..::.ObsoleteAttribute
System..::.ParamArrayAttribute
System.Reflection..::.AssemblyAlgorithmIdAttribute
System.Reflection..::.AssemblyCompanyAttribute
System.Reflection..::.AssemblyConfigurationAttribute
System.Reflection..::.AssemblyCopyrightAttribute
System.Reflection..::.AssemblyCultureAttribute
System.Reflection..::.AssemblyDefaultAliasAttribute
System.Reflection..::.AssemblyDelaySignAttribute
System.Reflection..::.AssemblyDescriptionAttribute
System.Reflection..::.AssemblyFileVersionAttribute
System.Reflection..::.AssemblyFlagsAttribute
System.Reflection..::.AssemblyInformationalVersionAttribute
System.Reflection..::.AssemblyKeyFileAttribute
System.Reflection..::.AssemblyKeyNameAttribute
System.Reflection..::.AssemblyMetadataAttribute
System.Reflection..::.AssemblyProductAttribute
System.Reflection..::.AssemblySignatureKeyAttribute
System.Reflection..::.AssemblyTitleAttribute
System.Reflection..::.AssemblyTrademarkAttribute
System.Reflection..::.AssemblyVersionAttribute
System.Reflection..::.DefaultMemberAttribute
System.Resources..::.NeutralResourcesLanguageAttribute
System.Resources..::.SatelliteContractVersionAttribute
System.Runtime.CompilerServices..::.AccessedThroughPropertyAttribute
System.Runtime.CompilerServices..::.CallerFilePathAttribute
System.Runtime.CompilerServices..::.CallerLineNumberAttribute
System.Runtime.CompilerServices..::.CallerMemberNameAttribute
System.Runtime.CompilerServices..::.CodeGenerationAttribute
System.Runtime.CompilerServices..::.CompilationRelaxationsAttribute
System.Runtime.CompilerServices..::.CompilerGeneratedAttribute
System.Runtime.CompilerServices..::.CustomConstantAttribute
System.Runtime.CompilerServices..::.DecimalConstantAttribute
System.Runtime.CompilerServices..::.DynamicAttribute
System.Runtime.CompilerServices..::.ExtensionAttribute
System.Runtime.CompilerServices..::.FixedBufferAttribute
System.Runtime.CompilerServices..::.IndexerNameAttribute
System.Runtime.CompilerServices..::.InternalsVisibleToAttribute
System.Runtime.CompilerServices..::.MethodImplAttribute
System.Runtime.CompilerServices..::.ReferenceAssemblyAttribute
System.Runtime.CompilerServices..::.RuntimeCompatibilityAttribute
System.Runtime.CompilerServices..::.StateMachineAttribute
System.Runtime.CompilerServices..::.TypeForwardedFromAttribute
System.Runtime.CompilerServices..::.TypeForwardedToAttribute
System.Runtime.CompilerServices..::.UnsafeValueTypeAttribute
System.Runtime.InteropServices..::.AllowReversePInvokeCallsAttribute
System.Runtime.InteropServices..::.ClassInterfaceAttribute
System.Runtime.InteropServices..::.CoClassAttribute
System.Runtime.InteropServices..::.ComDefaultInterfaceAttribute
System.Runtime.InteropServices..::.ComImportAttribute
System.Runtime.InteropServices..::.ComVisibleAttribute
System.Runtime.InteropServices..::.DefaultCharSetAttribute
System.Runtime.InteropServices..::.DispIdAttribute
System.Runtime.InteropServices..::.DllImportAttribute
System.Runtime.InteropServices..::.FieldOffsetAttribute
System.Runtime.InteropServices..::.GuidAttribute
System.Runtime.InteropServices..::.InAttribute
System.Runtime.InteropServices..::.InterfaceTypeAttribute
System.Runtime.InteropServices..::.MarshalAsAttribute
System.Runtime.InteropServices..::.OptionalAttribute
System.Runtime.InteropServices..::.OutAttribute
System.Runtime.InteropServices..::.PreserveSigAttribute
System.Runtime.InteropServices..::.StructLayoutAttribute
System.Runtime.InteropServices..::.UnmanagedFunctionPointerAttribute
System.Runtime.InteropServices.WindowsRuntime..::.DefaultInterfaceAttribute
System.Runtime.InteropServices.WindowsRuntime..::.InterfaceImplementedInVersionAttribute
System.Runtime.InteropServices.WindowsRuntime..::.ReadOnlyArrayAttribute
System.Runtime.InteropServices.WindowsRuntime..::.ReturnValueNameAttribute
System.Runtime.InteropServices.WindowsRuntime..::.WriteOnlyArrayAttribute
System.Runtime.Serialization..::.CollectionDataContractAttribute
System.Runtime.Serialization..::.ContractNamespaceAttribute
System.Runtime.Serialization..::.DataContractAttribute
System.Runtime.Serialization..::.DataMemberAttribute
System.Runtime.Serialization..::.EnumMemberAttribute
System.Runtime.Serialization..::.IgnoreDataMemberAttribute
System.Runtime.Serialization..::.KnownTypeAttribute
System.Runtime.Serialization..::.OnDeserializedAttribute
System.Runtime.Serialization..::.OnDeserializingAttribute
System.Runtime.Serialization..::.OnSerializedAttribute
System.Runtime.Serialization..::.OnSerializingAttribute
System.Runtime.Versioning..::.TargetFrameworkAttribute
System.Security..::.AllowPartiallyTrustedCallersAttribute
System.Security.Permissions..::.SecurityAttribute
System.Security..::.SecurityCriticalAttribute
System.Security..::.SecuritySafeCriticalAttribute
System.Security..::.SecurityTransparentAttribute
System.Security..::.UnverifiableCodeAttribute
System.ServiceModel..::.DataContractFormatAttribute
System.ServiceModel..::.FaultContractAttribute
System.ServiceModel..::.MessageContractAttribute
System.ServiceModel..::.MessageContractMemberAttribute
System.ServiceModel..::.MessageParameterAttribute
System.ServiceModel..::.OperationContractAttribute
System.ServiceModel..::.ServiceContractAttribute
System.ServiceModel..::.ServiceKnownTypeAttribute
System.ServiceModel..::.XmlSerializerFormatAttribute
System..::.STAThreadAttribute
System..::.ThreadStaticAttribute
System.Windows.Markup..::.ContentPropertyAttribute
System.Windows.Markup..::.XmlnsDefinitionAttribute
System.Windows.Markup..::.XmlnsPrefixAttribute
System.Windows..::.StyleTypedPropertyAttribute
System.Windows..::.TemplatePartAttribute
System.Windows..::.TemplateVisualStateAttribute
System.Xml.Serialization..::.XmlAnyAttributeAttribute
System.Xml.Serialization..::.XmlAnyElementAttribute
System.Xml.Serialization..::.XmlArrayAttribute
System.Xml.Serialization..::.XmlArrayItemAttribute
System.Xml.Serialization..::.XmlAttributeAttribute
System.Xml.Serialization..::.XmlChoiceIdentifierAttribute
System.Xml.Serialization..::.XmlElementAttribute
System.Xml.Serialization..::.XmlEnumAttribute
System.Xml.Serialization..::.XmlIgnoreAttribute
System.Xml.Serialization..::.XmlIncludeAttribute
System.Xml.Serialization..::.XmlNamespaceDeclarationsAttribute
System.Xml.Serialization..::.XmlRootAttribute
System.Xml.Serialization..::.XmlSchemaProviderAttribute
System.Xml.Serialization..::.XmlTextAttribute
System.Xml.Serialization..::.XmlTypeAttribute