CHAPTER 15 TYPE REFLECTION, LATE BINDING, AND ATTRIBUTE-BASED PROGRAMMING
// Cast to get access to the members of MiniVan?
// Nope! Compiler error!
object obj = (MiniVan)Activator.CreateInstance(minivan);
However, because your program has not set a reference to CarLibrary.dll, you cannot make use of
the C# using keyword to import the CarLibrary namespace and, therefore, you can’t use a MiniVan
during the casting operation! Remember that the whole point of late binding is to create instances of
objects for which there is no compile-time knowledge. Given this, how can you invoke the underlying
methods of the MiniVan object stored in the System.Object reference? The answer, of course, is by using
reflection.
Invoking Methods with No Parameters
Assume you wish to invoke the TurboBoost() method of the MiniVan. As you recall, this method will set
the state of the engine to “dead” and display an informational message box. The first step is to obtain a
MethodInfo object for the TurboBoost() method using Type.GetMethod(). From the resulting MethodInfo,
you are then able to call MiniVan.TurboBoost using Invoke(). MethodInfo.Invoke() requires you to send
in all parameters that are to be given to the method represented by MethodInfo. These parameters are
represented by an array of System.Object types (as the parameters for a given method could be any
number of various entities).
Given that TurboBoost() does not require any parameters, you can simply pass null (meaning “this
method has no parameters”). Update your CreateUsingLateBinding() method as follows:
static void CreateUsingLateBinding(Assembly asm)
{
try
{
// Get metadata for the Minivan type.
Type miniVan = asm.GetType("CarLibrary.MiniVan");
// Create the Minivan on the fly.
object obj = Activator.CreateInstance(miniVan);
Console.WriteLine("Created a {0} using late binding!", obj);
// Get info for TurboBoost.
MethodInfo mi = miniVan.GetMethod("TurboBoost");
// Invoke method ('null' for no parameters).
mi.Invoke(obj, null);
}
}
catch(Exception ex)
{
Console.WriteLine(ex.Message);
}
At this point, you will see the message box shown in Figure 15-2, once the TurboBoost() method is
invoked.
576