Attribute Class

July 28, 2014

Represents the base class for custom attributes.

System.Object
  System.Attribute
    More...

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

[AttributeUsageAttribute(AttributeTargets.All, Inherited = true, AllowMultiple = false)]
public abstract class Attribute

The Attribute type exposes the following members.

  NameDescription
Protected methodAttributeInitializes a new instance of the Attribute class.
Top

  NameDescription
Public methodEqualsInfrastructure. Returns a value that indicates whether this instance is equal to a specified object. (Overrides Object.Equals(Object).)
Protected methodFinalizeAllows an object to try to free resources and perform other cleanup operations before the Object is reclaimed by garbage collection. (Inherited from Object.)
Public methodStatic memberGetCustomAttribute(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.
Public methodStatic memberGetCustomAttribute(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.
Public methodStatic memberGetCustomAttribute(Module, Type)Retrieves a custom attribute applied to a module. Parameters specify the module, and the type of the custom attribute to search for.
Public methodStatic memberGetCustomAttribute(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.
Public methodStatic memberGetCustomAttribute(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.
Public methodStatic memberGetCustomAttribute(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.
Public methodStatic memberGetCustomAttribute(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.
Public methodStatic memberGetCustomAttribute(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.
Public methodStatic memberGetCustomAttributes(Assembly)Retrieves an array of the custom attributes applied to an assembly. A parameter specifies the assembly.
Public methodStatic memberGetCustomAttributes(MemberInfo)Retrieves an array of the custom attributes applied to a member of a type. A parameter specifies the member.
Public methodStatic memberGetCustomAttributes(Module)Retrieves an array of the custom attributes applied to a module. A parameter specifies the module.
Public methodStatic memberGetCustomAttributes(ParameterInfo)Retrieves an array of the custom attributes applied to a method parameter. A parameter specifies the method parameter.
Public methodStatic memberGetCustomAttributes(Assembly, Boolean)Retrieves an array of the custom attributes applied to an assembly. Parameters specify the assembly, and an ignored search option.
Public methodStatic memberGetCustomAttributes(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.
Public methodStatic memberGetCustomAttributes(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.
Public methodStatic memberGetCustomAttributes(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.
Public methodStatic memberGetCustomAttributes(Module, Boolean)Retrieves an array of the custom attributes applied to a module. Parameters specify the module, and an ignored search option.
Public methodStatic memberGetCustomAttributes(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.
Public methodStatic memberGetCustomAttributes(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.
Public methodStatic memberGetCustomAttributes(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.
Public methodStatic memberGetCustomAttributes(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.
Public methodStatic memberGetCustomAttributes(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.
Public methodStatic memberGetCustomAttributes(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.
Public methodStatic memberGetCustomAttributes(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.
Public methodGetHashCodeReturns the hash code for this instance. (Overrides Object.GetHashCode().)
Public methodGetTypeGets the Type of the current instance. (Inherited from Object.)
Public methodStatic memberIsDefined(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.
Public methodStatic memberIsDefined(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.
Public methodStatic memberIsDefined(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.
Public methodStatic memberIsDefined(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.
Public methodStatic memberIsDefined(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.
Public methodStatic memberIsDefined(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.
Public methodStatic memberIsDefined(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.
Public methodStatic memberIsDefined(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.
Public methodMatchWhen overridden in a derived class, returns a value that indicates whether this instance equals a specified object.
Protected methodMemberwiseCloneCreates a shallow copy of the current Object. (Inherited from Object.)
Public methodToStringReturns a string that represents the current object. (Inherited from Object.)
Top

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.

The following code example demonstrates the usage of 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.
 */


Windows Phone OS

Supported in: 8.1, 8.0, 7.1, 7.0

Windows Phone

This type is thread safe.

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

Show:
© 2014 Microsoft