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 Attribute.GetCustomAttributes, 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 the positional arguments and named arguments of the attribute. Use the ConstructorArguments property to get a list of CustomAttributeTypedArgument structures that represent the positional arguments, and use the NamedArguments property to get a list of CustomAttributeNamedArgument structures that represent the named arguments.

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 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 example defines a custom attribute with four constructors and four properties. Two of the properties are read-only, and are set by using the positional parameters of the constructors. The other two properties are read/write, and can be set only by using named arguments. One positional property is an array of strings, and one named property is an array of integers.

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. Different constructors are used for these cases. 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.

The attribute that is applied to the type demonstrates array properties, with both positional and named arguments.