Search code examples
c#linqreflectionlinq-to-objects

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

Solution

  • 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"));