Free mag vol1 | Page 632

CHAPTER 15  TYPE REFLECTION, LATE BINDING, AND ATTRIBUTE-BASED PROGRAMMING } } Console.ReadLine(); }  Source Code The SharedAsmReflector project is included in the Chapter 15 subdirectory. At this point, you should understand how to use some of the core members of the System.Reflection namespace to discover metadata at runtime. Of course, I realize despite the “cool factor,” you likely will not need to build custom object browsers at your place of employment too often. Do recall, however, that reflection services are the foundation for a number of very common programming activities, including late binding. Understanding Late Binding Simply put, late binding is a technique in which you are able to create an instance of a given type and invoke its members at runtime without having hard-coded compile-time knowledge of its existence. When you are building an application that binds late to a type in an external assembly, you have no reason to set a reference to the assembly; therefore, the caller’s manifest has no direct listing of the assembly. At first glance, it is not easy to see the value of late binding. It is true that if you can “bind early” to an object (e.g., set an assembly reference and allocate the type using the C# new keyword), you should opt to do so. For one reason, early binding allows you to determine errors at compile time, rather than at runtime. Nevertheless, late binding does have a critical role in any extendable application you may be building. You will have a chance to build such an “extendable” program at the end of this chapter, in the section “Building an Extendable Application”; until then, let’s examine the role of the Activator class. The System.Activator Class The System.Activator class (defined in mscorlib.dll) is the key to the .NET late-binding process. For the current example, you are only interested in the Activator.CreateInstance() method, which is used to create an instance of a type à la late binding. This method has been overloaded numerous times to provide a good deal of flexibility. The simplest variation of the CreateInstance() member takes a valid Type object that describes the entity you wish to allocate into memory on the fly. Create a new Console Application named LateBindingApp, and import the System.IO and System.Reflection namespace via the C# using keyword. Now, update the Program class as follows: // This program will load an external library, // and create an object using late binding. public class Program { static void Main(string[] args) { Console.WriteLine("***** Fun with Late Binding *****"); // Try to load a local copy of CarLibrary. Assembly a = null; 574