In Chapter 5 you will learn about attributes: how to use some of the interesting existing attributes and how to create customer attributes. We'll leap ahead a bit for a moment and take a look at the mechanics of requesting attributes by using Reflection. At the heart of our technical demonstration is the Attribute class and the GetCustomAttributes method. Listing 4.15 demonstrates how to request attributes for a specific type. (In Chapter 5 you will learn that any element might have attributes applied; the same code demonstrated in Chapter 5 will return Reflected attributes for members as well as types.)
Listing 4.15 Reflecting Attributes
Dim Attributes() As Object Attributes = GetType(Customer).GetCustomAttributes(True) Dim A As Attribute For Each A In Attributes If (TypeOf A Is DescriptionAttribute) Then Debug.WriteLine(CType(A, DescriptionAttribute).Description) End If Next
The first step is to determine whether you want one or all of the attributes. In our example we want all of the attributes for a type; thus we declare an array of objects. ( GetCustomAttributes returns an array of objects that are actually attributes.) The second statement requests all the attributes for the type of Customer . The argument True passed to GetCustomAttributes instructs Reflection to search ancestors for inherited attributes too. Pass False to GetCustomAttributes to ignore ancestral attributes.
The remaining code simply iterates through the array of attributes returned. In Listing 4.15 we are specifically looking for the DescriptionAttribute object defined in the System.ComponentModel . If any of the attributes applied to the type are DescriptionAttribute objects, the Description property of the attribute is written to the Output window.