Thursday, April 19, 2012

Reflection: Dynamically instantiating a class

The requirement was for a command line utility that accepted a "function" name and a list of parameters, where the parameters could be different for each function.

This is a fairly common requirement, which I don't want to have to look up again, so I thought I'd document my solution here.

My first thought was a switch on the function name, but that quickly became messy with the variable parameters. After consideration, it was simpler to implement each function as a class, then use reflection to instantiate the class and pass in command line parameters. To support dynamically creating the class, I used a common Interface with a Run method that accepted the command line parameters.

 namespace CodeExamples  
 {  
   interface IExample  
   {  
     void Run(string[] args);  
   }    
   class Program  
   {  
     static void Main(string[] args)  
     {  
       try  
       {  
         if (args.Length < 1)  
         {  
           Console.WriteLine("Syntax: CodeExample typeName [args]");  
         }  
         else  
         {  
           string assemblyName = "CodeExamples.";  
           string typeName = args[0];  
           Assembly = System.Reflection.Assembly.GetExecutingAssembly();  
           Type type = assembly.GetType(assemblyName + typeName);  
           IExample example = (IExample)Activator.CreateInstance(type);  
           example.Run(args);  
         }  
       }  
       catch (Exception e)  
       {  
         Console.WriteLine("\nEXCEPTION: {0}\n{1}", e.Message, e.StackTrace);  
       }  
     }  
   }  
 }