Free mag vol1 | Page 637

CHAPTER 15  TYPE REFLECTION, LATE BINDING, AND ATTRIBUTE-BASED PROGRAMMING [Obsolete] Marks a deprecated type or member. If other programmers attempt to use such an item, they will receive a compiler warning describing the error of their ways. [Serializable] Marks a class or structure as being “serializable,” meaning it is able to persist its current state into a stream. [NonSerialized] Specifies that a given field in a class or structure should not be persisted during the serialization process. [ServiceContract] Marks a method as a contract implemented by a WCF service. Understand that when you apply attributes in your code, the embedded metadata is essentially useless until another piece of software explicitly reflects over the information. If this is not the case, the blurb of metadata embedded within the assembly is ignored and completely harmless. Attribute Consumers As you would guess, the .NET 4.5 Framework SDK ships with numerous utilities that are indeed on the lookout for various attributes. The C# compiler (csc.exe) itself has been preprogrammed to discover the presence of various attributes during the compilation cycle. For example, if the C# compiler encounters the [CLSCompliant] attribute, it will automatically check the attributed item to ensure it is exposing only CLS-compliant constructs. By way of another example, if the C# compiler discovers an item attributed with the [Obsolete] attribute, it will display a compiler warning in the Visual Studio Error List window. In addition to development tools, numerous methods in the .NET base class libraries are preprogrammed to reflect over specific attributes. For example, if you wish to persist the state of an object to file, all you are required to do is annotate your class or structure with the [Serializable] attribute. If the Serialize() method of the BinaryFormatter class encounters this attribute, the object is automatically persisted to file in a compact binary format. Finally, you are free to build applications that are programmed to reflect over your own custom attributes, as well as any attribute in the .NET base class libraries. By doing so, you are essentially able to create a set of “keywords” that are understood by a specific set of assemblies. Applying Attributes in C# To illustrate the process of applying attributes in C#, create a new Console Application named ApplyingAttributes. Assume you wish to build a class named Motorcycle that can be persisted in a binary format. To do so, simply apply the [Serializable] attribute to the class definition. If you have a field that should not be persisted, you may apply the [NonSerialized] attribute. // This class can be saved to disk. [Serializable] public class Motorcycle { // However, this field will not be persisted. [NonSerialized] float weightOfCurrentPassengers; 579