views:

1069

answers:

4

I have an Interface called IStep that can do some computation (See "Execution in the Kingdom of Nouns"). At runtime, I want to select the appropriate implementation by class name.

// use like this:
IStep step = GetStep(sName);
+1  A: 

If the implementation has a parameterless constructor, you can do this using the System.Activator class. You will need to specify the assembly name in addition to the class name:

IStep step = System.Activator.CreateInstance(sAssemblyName, sClassName).Unwrap() as IStep;

http://msdn.microsoft.com/en-us/library/system.activator.createinstance.aspx

Ian Nelson
+3  A: 

Your question is very confusing...

If you want to find types that implement IStep, then do this:

foreach (Type t in Assembly.GetCallingAssembly().GetTypes())
{
  if (!typeof(IStep).IsAssignableFrom(t)) continue;
  Console.WriteLine(t.FullName + " implements " + typeof(IStep).FullName);
}

If you know already the name of the required type, just do this

IStep step = (IStep)Activator.CreateInstance(Type.GetType("MyNamespace.MyType"));
lubos hasko
A: 
Daren Thomas
A: 

Well Assembly.CreateInstance would seem to be the way to go - the only problem with this is that it needs the fully qualified name of the type, i.e. including the namespace.

samjudson