-2

I have multiple classes in a namespace implementing certain interface, and I want to make a list of all classes, that match the same interface.

Is there a way to reach that using System.Reflection?

public interface A
{}
public class AB : A
{}
public class AC : A
{}
public class AD : A
{}

List<A> classList = { AB, AC, AD};

Thanks.

Soner Gönül
  • 97,193
  • 102
  • 206
  • 364
JohnyGomez
  • 117
  • 1
  • 8
  • how is is this duplicate if he asks about the namespaces and the question is answering about assemblies? – cikatomo Feb 13 '22 at 15:17

3 Answers3

1

try this

            var interfaceType = typeof(A);
            var classes = AppDomain.CurrentDomain.GetAssemblies()
                .SelectMany(s => s.GetTypes())
                .Where(interfaceType.IsAssignableFrom).ToList();
            classes.Remove(typeof(A));
Alyafey
  • 1,455
  • 3
  • 15
  • 23
0

Yes. You will need to know which assembly the types are in. Then get the types from that assembly, and find the ones that implement your interface.

Assembly a = typeof(A).Assembly;
var list = a.GetTypes().Where(type => type != typeof(A) && typeof(A).IsAssignableFrom(type)).ToList();
driis
  • 161,458
  • 45
  • 265
  • 341
-1

Yes, see Type.implementsInterface for more information. http://msdn.microsoft.com/en-us/library/bb383789(v=vs.100).aspx

You can also use typeof(IWhateverable).IsAssignableFrom(myType)

More information from here: http://www.hanselman.com/blog/DoesATypeImplementAnInterface.aspx

Panu Oksala
  • 3,245
  • 1
  • 18
  • 28