Creating objects dynamically with C# 2.0

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
            return (IPayment)Activator.CreateInstance(t);
        }

Works well as a simple example, and demonstrates the important concepts.

Download the full code here:
http://blog.benhall.me.uk/Code/DynamicFactory/Program.cs.txt

Let me know what you think.

4 thoughts on “Creating objects dynamically with C# 2.0”

  1. System.ArgumentNullException was unhandled
    Message=”Value cannot be null.rnParameter name: type”
    Source=”mscorlib”
    ParamName=”type”
    StackTrace:
    at System.Activator.CreateInstance(Type type, Boolean nonPublic)
    at System.Activator.CreateInstance(Type type)
    at DynamicFactory.Factory.GetPaymentObject() in E:TestCreateObjectCreateObjectCreateObjectProgram.cs:line 99
    at DynamicFactory.Program.Main(String[] args) in E:TestCreateObjectCreateObjectCreateObjectProgram.cs:line 60
    at System.AppDomain.nExecuteAssembly(Assembly assembly, String[] args)
    at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
    at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
    at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
    at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
    at System.Threading.ThreadHelper.ThreadStart()

    I get above exception at this line “return (IPayment)Activator.CreateInstance(t);” in GetPaymentObject().

    For some reason, t=null

    Help
    mitendra.anand@in.abb.com

Leave a Reply

Your email address will not be published. Required fields are marked *