Late Binding

Reflection can also perform late binding, in which the application dynamically loads, instantiates, and uses a type at runtime. This provides greater flexibility at the expense of invocation overhead.

In this section, we create an example that uses very late binding, dynamically discovers new types at runtime, and uses them as well.

In the next example, one or more assemblies are loaded by name (as specified on the command line) and iterated through the types in the assembly looking for subtypes of the Greeting abstract base class. When one is found, the type is instantiated and its SayHello() method invoked, which displays an appropriate greeting.

To perform the runtime discovery of types, we use an abstract base class that’s compiled into an assembly as follows (see the source comment for filename and compilation information):

// Greeting.cs - compile with /t:library
public abstract class Greeting { 
  public abstract void SayHello();
}

Compiling this code produces a file named Greeting.dll, which the other parts of the sample can use.

We now create a new assembly containing two concrete subtypes of the abstract type Greeting, as follows (see the source comment for filename and compilation information):

// English.cs - compile with /t:library /r:Greeting.dll using System; public class AmericanGreeting : Greeting { private string msg = "Hey, dude. Wassup!"; public override void SayHello() { Console.WriteLine(msg); } } public class BritishGreeting : Greeting { private string ...

Get C# in a Nutshell now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.