Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find an implementation of a C# interface in the current assembly with a specific name?

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);
like image 736
Daren Thomas Avatar asked Aug 21 '08 11:08

Daren Thomas


2 Answers

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"));
like image 53
lubos hasko Avatar answered Nov 03 '22 00:11

lubos hasko


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

like image 22
Ian Nelson Avatar answered Nov 03 '22 00:11

Ian Nelson