CHAPTER 15 TYPE REFLECTION, LATE BINDING, AND ATTRIBUTE-BASED PROGRAMMING
// Invoke TurnOnRadio() with arguments.
MethodInfo mi = sport.GetMethod("TurnOnRadio");
mi.Invoke(obj, new object[] { true, 2 });
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
Hopefully, at this point, you can see the relationships among reflection, dynamic loading, and late
binding. To be sure, the reflection API provides many additional features beyond what has been covered
here, but you should be in good shape to dig into more details if you are interested.
Again, you still might wonder exactly when you should make use of these techniques in your own
applications. The conclusion of this chapter should shed light on this issue; however, the next topic
under investigation is the role of .NET attributes.
Source Code The Late BindingApp project is included in the Chapter 15 subdirectory.
Understanding the Role of .NET Attributes
As illustrated at beginning of this chapter, one role of a .NET compiler is to generate metadata
descriptions for all defined and referenced types. In addition to this standard metadata contained within
any assembly, the .NET platform provides a way for programmers to embed additional metadata into an
assembly using attributes. In a nutshell, attributes are nothing more than code annotations that can be
applied to a given type (class, interface, structure, etc.), member (property, method, etc.), assembly, or
module.
.NET attributes are class types that extend the abstract System.Attribute base class. As you explore
the .NET namespaces, you will find many predefined attributes that you are able to make use of in your
applications. Furthermore, you are free to build custom attributes to further qualify the behavior of your
types by creating a new type deriving from Attribute.
The .NET base class library provides a number of attributes in various namespaces. Table 15-3 gives
a snapshot of some—but by absolutely no means all—predefined attributes.
Table 15-3. A Tiny Sampling of Predefined Attributes
578
Attribute
Meaning in Life
[CLSCompliant]
Enforces the annotated item to conform to the rules of the Common
Language Specification (CLS). Recall that CLS-compliant types are
guaranteed to be used seamlessly across all .NET programming languages.
[DllImport]
Allows .NET code to make calls to any unmanaged C- or C++-based code
library, including the API of the underlying operating system. Do note that
[DllImport] is not used when communicating with COM-based software.