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);
}
}
}
}