Creating objects dynamically with C# 2.0
So I have been playing with some code this morning on how to create objects in the assembly dynamically just based on their class name.
Basically, I created a console application with an interface and three subclasses. The application will print out a list of object names they could create, and asks the user to select which one to create. Based on the user input, the name is passed into the method below and returns an object of type IPayment (the interface). The console application then calls a method on the object which returns its name and prints it out to the console. Simple but effective.
This is the most important method, which does most of the work.
public static IPayment GetPaymentObject(string className)
//Get the current assembly object
Assembly assembly = Assembly.GetExecutingAssembly();
//Get the name of the assembly (this will include the public token and version number
AssemblyName assemblyName = assembly.GetName();
//Use just the name concat to the class chosen to get the type of the object
Type t = assembly.GetType(assemblyName.Name + “.” + className);
//Create the object, cast it and return it to the caller
Works well as a simple example, and demonstrates the important concepts.
Download the full code here:
Let me know what you think.