Free mag vol1 | Page 642

CHAPTER 15  TYPE REFLECTION, LATE BINDING, AND ATTRIBUTE-BASED PROGRAMMING { } [VehicleDescription("A very long, slow, but feature-rich auto")] public class Winnebago { } Named Property Syntax Notice that the description of the Motorcycle is assigned a description using a new bit of attributecentric syntax termed a named property. In the constructor of the first [VehicleDescription] attribute, you set the underlying string data by using the Description property. If this attribute is reflected upon by an external agent, the value is fed into the Description property (named property syntax is legal only if the attribute supplies a writable .NET property). In contrast, the HorseAndBuggy and Winnebago types are not making use of named property syntax and are simply passing the string data via the custom constructor. In any case, once you compile the AttributedCarLibrary assembly, you can make use of ildasm.exe to view the injected metadata descriptions for your type. For example, Figure 15-5 shows an embedded description of the Winnebago class, specifically the data within the beforefieldinit item in ildasm.exe. Figure 15-5. Embedded vehicle description data Restricting Attribute Usage By default, custom attributes can be applied to just about any aspect of your code (methods, classes, properties, and so on). Thus, if it made sense to do so, you could use VehicleDescription to qualify methods, properties, or fields (among other things). [VehicleDescription("A very long, slow, but feature-rich auto")] public class Winnebago { [VehicleDescription("My rocking CD player")] public void PlayMusic(bool On) { ... } } 584