-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
  • 94,086
  • 102
  • 195
  • 339
JohnyGomez
  • 97
  • 1
  • 7
  • 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,435
  • 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
  • 156,816
  • 44
  • 266
  • 336
-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,105
  • 1
  • 16
  • 28