CustomAttributeData Class

Note: This class is new in the .NET Framework version 2.0.

Provides access to custom attribute data for assemblies, modules, types, members and parameters that are loaded into the reflection-only context.

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

'Declaration
<SerializableAttribute> _
<ComVisibleAttribute(True)> _
Public NotInheritable Class CustomAttributeData
'Usage
Dim instance As CustomAttributeData

/** @attribute SerializableAttribute() */ 
/** @attribute ComVisibleAttribute(true) */ 
public final class CustomAttributeData
SerializableAttribute 
ComVisibleAttribute(true) 
public final class CustomAttributeData

Code that is being examined in the reflection-only context cannot be executed, so it is not always possible to examine custom attributes by creating instances of them and then examining their properties, using methods like System.Attribute.GetCustomAttributes, System.Reflection.MemberInfo.GetCustomAttributes, and so on. If the code for the attribute type itself is loaded into the reflection-only context, it cannot be executed.

The CustomAttributeData class allows examination of custom attributes in the reflection-only context by providing an abstraction for attributes. The members of this class can be used to obtain values for the positional arguments and named arguments of the attribute. For enumerations, the value is provided using the underlying type of the enumeration. The name of the enumeration is supplied along with the value, in the CustomAttributeTypedArgument structure.

CustomAttributeData can be used in the execution context as well as in the reflection-only context. For example, you might want to avoid loading the assembly that contains the code for a custom attribute. Using the CustomAttributeData class is different from using methods like System.Attribute.GetCustomAttributes:

  • The properties and methods of CustomAttributeData only provide you with the values that were specified for the attribute instance, not the semantics of the constructor. For example, a string argument of an attribute might be converted internally to some other representation, and returned in a canonical form; or a property might have side effects when the actual attribute code is executed.

  • The properties and methods of CustomAttributeData do not allow you to retrieve the custom attributes inherited from base classes.

To create instances of the CustomAttributeData class, use the static (Shared in Visual Basic) GetCustomAttributes factory methods.

The following code example defines a custom attribute with two constructors and one property. The attribute is applied to the assembly, to a type declared in the assembly, to a method of the type, and to a parameter of the method. When executed, the assembly loads itself into the reflection-only context and displays information about the custom attributes that were applied to it and to the type and members it contains.

Imports System
Imports System.Reflection
Imports System.Collections.Generic

' The example attribute is applied to the assembly.
<Assembly:Example(ExampleKind.ThirdKind, Note:="This is a note on the assembly.")>

' An enumeration used by the ExampleAttribute class.
Public Enum ExampleKind
    FirstKind
    SecondKind
    ThirdKind
    FourthKind
End Enum

' An example attribute. The attribute can be applied to all
' targets, from assemblies to parameters.
'
<AttributeUsage(AttributeTargets.All)> _
Public Class ExampleAttribute
    Inherits Attribute

    ' Data for properties.
    Private kindValue As ExampleKind
    Private noteValue As String

    ' Constructors. The parameterless constructor (.ctor) calls
    ' the constructor that specifies ExampleKind, and supplies the
    ' default value.
    '
    Public Sub New(ByVal initKind As ExampleKind)
        kindValue = initKind
    End Sub
    Public Sub New()
        Me.New(ExampleKind.FirstKind)
    End Sub

    ' Properties. The Note property must be read/write, so that it can
    ' be used as a named parameter.
    '
    Public ReadOnly Property Kind As ExampleKind
        Get
            Return kindValue 
        End Get
    End Property
    Public Property Note As String
        Get
            Return noteValue 
        End Get
        Set
            noteValue = value
        End Set
    End Property
End Class

' The example attribute is applied to the test class.
'
<Example(ExampleKind.SecondKind, Note:="This is a note on the class.")> _
Public Class Test
    ' The example attribute is applied to a method, using the
    ' parameterless constructor and supplying a named argument.
    ' The attribute is also applied to the method parameter.
    '
    <Example(Note:="This is a note on a method.")> _
    Public Sub TestMethod(<Example()> ByVal arg As Object)
    End Sub

    ' Sub Main gets objects representing the assembly, the test
    ' type, the test method, and the method parameter. Custom
    ' attribute data is displayed for each of these.
    '
    Public Shared Sub Main()
        Dim asm As [Assembly] = Assembly.ReflectionOnlyLoad("Source")
        Dim t As Type = asm.GetType("Test")
        Dim m As MethodInfo = t.GetMethod("TestMethod")
        Dim p() As ParameterInfo = m.GetParameters()

        Console.WriteLine(vbCrLf & "Attributes for assembly: {0}", asm)
        ShowAttributeData(CustomAttributeData.GetCustomAttributes(asm))
        Console.WriteLine(vbCrLf & "Attributes for type: {0}", t)
        ShowAttributeData(CustomAttributeData.GetCustomAttributes(t))
        Console.WriteLine(vbCrLf & "Attributes for member: {0}", m)
        ShowAttributeData(CustomAttributeData.GetCustomAttributes(m))
        Console.WriteLine(vbCrLf & "Attributes for parameter: {0}", p)
        ShowAttributeData(CustomAttributeData.GetCustomAttributes(p(0)))
    End Sub

    Private Shared Sub ShowAttributeData( _
        ByVal attributes As IList(Of CustomAttributeData))

        For Each cad As CustomAttributeData _
            In CType(attributes, IEnumerable(Of CustomAttributeData))

            Console.WriteLine("   {0}", cad)
            Console.WriteLine("      Constructor: {0}", cad.Constructor)

            Console.WriteLine("      Constructor arguments:")
            For Each cata As CustomAttributeTypedArgument _
                In CType(cad.ConstructorArguments, IEnumerable(Of CustomAttributeTypedArgument))

                Console.WriteLine("         Type: {0} Value: {1}", _
                    cata.ArgumentType, cata.Value)
            Next

            Console.WriteLine("      Named arguments:")
            For Each cana As CustomAttributeNamedArgument _
                In CType(cad.NamedArguments, IEnumerable(Of CustomAttributeNamedArgument))

                Dim cata As CustomAttributeTypedArgument = _
                    cana.TypedValue
                Console.WriteLine("         MemberInfo: {0}", _
                    cana.MemberInfo)
                Console.WriteLine("         Type: {0} Value: {1}", _
                    cata.ArgumentType, cata.Value)
            Next
        Next
    End Sub
End Class

' This code example produces output similar to the following:
'
'Attributes for assembly: source, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null
'   [ExampleAttribute((ExampleKind)2, Note = "This is a note on the assembly.")]
'      Constructor: Void .ctor(ExampleKind)
'      Constructor arguments:
'         Type: ExampleKind Value: 2
'      Named arguments:
'         MemberInfo: System.String Note
'         Type: System.String Value: This is a note on the assembly.
'   [System.Runtime.CompilerServices.CompilationRelaxationsAttribute((Int32)8)]
'      Constructor: Void .ctor(Int32)
'      Constructor arguments:
'         Type: System.Int32 Value: 8
'      Named arguments:
'
'Attributes for type: Test
'   [ExampleAttribute((ExampleKind)1, Note = "This is a note on the class.")]
'      Constructor: Void .ctor(ExampleKind)
'      Constructor arguments:
'         Type: ExampleKind Value: 1
'      Named arguments:
'         MemberInfo: System.String Note
'         Type: System.String Value: This is a note on the class.
'
'Attributes for member: Void TestMethod(System.Object)
'   [ExampleAttribute(Note = "This is a note on a method.")]
'      Constructor: Void .ctor()
'      Constructor arguments:
'      Named arguments:
'         MemberInfo: System.String Note
'         Type: System.String Value: This is a note on a method.
'
'Attributes for parameter: System.Object arg
'   [ExampleAttribute()]
'      Constructor: Void .ctor()
'      Constructor arguments:
'      Named arguments:

System.Object
  System.Reflection.CustomAttributeData

Any public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe.

Windows 98, Windows 2000 SP4, Windows Millennium Edition, Windows Server 2003, Windows XP Media Center Edition, Windows XP Professional x64 Edition, Windows XP SP2, Windows XP Starter Edition

The .NET Framework does not support all versions of every platform. For a list of the supported versions, see System Requirements.

.NET Framework

Supported in: 2.0

Community Additions

ADD
Show: