1

At the moment I have a list of classes like this:

public List<Algo> AlgoList = new List<Algo>
{
    new BastionAlgo(),
    new BitcoreAlgo(),
    new Blake2SAlgo(),
    new BlakeAlgo(),
    new BlakeCoinAlgo(),
    new BmwAlgo(),
    new C11FlaxAlgo(),
    new CryptolightAlgo(),
    new CryptonightAlgo(),
    ...
};

As I add and remove classes I would prefer not to have to maintain a long list. Is there a way to find and instantiate all the classes that extend another in .net core 2?

Thank you in advance for you assistance.

Alex Haslam
  • 3,269
  • 1
  • 13
  • 20
  • This question, as asked, is a poor fit for SO. But the term you are looking for is Reflection. A little Google-Fu should net you quite a few results. – Sam Axe Sep 14 '17 at 20:08
  • I should have include the research I had done. How would you recommend improving the "fit"? – Alex Haslam Sep 14 '17 at 20:17
  • I think I didn't give your question much thought before commenting. I apologize. The first glance looked like you were asking for a tutorial to me. But on further review I see my mistake. Please ignore my previous comment. – Sam Axe Sep 14 '17 at 20:20

1 Answers1

5

Yes there is, see Getting all types that implement an interface

var type = typeof(Algo);
var types = AppDomain.CurrentDomain.GetAssemblies()
    .SelectMany(s => s.GetTypes())
    .Where(p => type.IsAssignableFrom(p));

If they all have parameterless constructors you can use Activator.CreateInstance to create instances

AlgoList = types.Select(t => Activator.CreateInstance(t)).ToList();
Justin
  • 84,773
  • 49
  • 224
  • 367