How can I get a class into a variable to call function and get properties?
I have been told to look into reflection but I don't get how it's done when the DLL was not known at compile time.
To be clear: I have a 'main' class which loads an DLL and I want to create an instance of a class within the DLL and directly get properties.
Example. Here is a method I use that searches a plug-in directory tree and returns a list of WPF ValueConverter classes...
The code searches through the directory tree for files matching 'dll' and 'exe'. When it finds one, it attempts to load it and then looks to see if there's any WPF ValueConverters in it.
If it finds one, the code creates an instances and adds it to the list, and ultimately returns the list. Of course the 'dll's' and 'exe's' must be in the managed world. And if you were interested in classes other than ValueConverters, you would have to change it accordingly.
This is a purpose built method (i.e., I know what's going to happen with the result) and the code is given here only as an example...
In case you are talking about another .NET dll you can use this to load the assembly and get all the types in there:
You can instantiate an object with either the
Activator
:or you can get a list of all public constructors for that type with
GetConstructors
:However unless you know what type you are looking for and what its constructor parameters are it is a bit pointless to try to instatiate and use it.
Write your self an Interface (IKnowAboutSomething) that is accessible via your Loaded DLL and also your Loading Program.
Scan through your Loaded DLL and find the classes which implement this interface.
Then you can use Activator.CreateInstance to create an instance of the Types you found (where you know the interface)
Now you just call methods on your IKnowAboutSomething.GetThingINeed() etc and you can interact with things you don't know about at compile time. (Well you know a little bit because they are using the Interface and therefore have an agreement)
Place this code in an External DLL (eg Core.Dll) that is accessible by both projects.
Now in your Main Project add a Reference to the above DLL.
In your main project scan a directory for the DLL's you are planning to load (c:\myDlls*.dll) use a DirectoryInfo (or similar) to scan.
Once you have found a DLL, use the Assembly asm = Assembly.LoadFrom(filename) to get it loaded.
Now you can do this in the main project.
You should do something like this:
EDIT
Naturally, the
DLL
has to be a managed DLL (so written in.NET
language)I didn't compile this, honestly, but basically this is an idea of how to do that.
Here also an example, that may help.