Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# polymorphism - load classes from DLL files

Tags:

c#

oop

dll

The responses I've got to this question have solved the problem I had in that question, but I'm wondering whether it's possible to extend it a bit. For example, if I were to have third parties contributing commands to this system, would there be a way of extending the first answer to my previous question to allow it to load all the commands from all the DLLs in a folder, and then list them in the list box.

Is that possible? Would it be able to work with a List of ICommand (as the answer to my previous question suggested).

like image 347
robintw Avatar asked May 21 '26 12:05

robintw


1 Answers

Yes.

 Assembly commandAssembly = Assembly.Load("some/path")
 var commands = new List<ICommand>();

 foreach (Type type in commandAssembly.GetTypes())
 {
    if (type.GetInterface(typeof(ICommand).FullName) != null)
    {
       commands.Add((ICommand)Activator.CreateInstance(type));
    }
 }

However, you will probably run into some restrictions regarding assembly loading. You cannot just load assemblies from anywhere, otherwise you could reimplement something like COM DLL hell.

like image 153
Wim Coenen Avatar answered May 23 '26 00:05

Wim Coenen



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!