Reputation: 367
atm Im "playing" a bit with the things C# can do - just to know how it works. Now I had the idea to load a class from a dll in runtime that extends a class from my original program. Example:
// My class in the dll.
namespace MyDll
{
public class MyClassInDll : MyClass
{
public MyClassInDll(int num) : base(num)
{
// May contain more code :)
}
}
}
// My abstract class which is inherited in the dll.
namespace MyProgram
{
public class MyClass
{
private int num;
public MyClass(int numToUse)
{
num = numToUse;
}
public void WriteTheNumber()
{
Console.WriteLine(num);
}
}
}
// My mainfile.
namespace MyProgram
{
public class Program
{
public void Main(String[] args)
{
// Load the DLL
Assembly dll = Assembly.LoadFile("myDll.dll");
// Create an instance of MyClassInDll stored as MyClass.
MyClass myclass = ? // I dont know what to enter here :(
// Call the function my program knows from MyClass
myclass.WriteTheNumber(); // this should write the in the constructor passed integer to the console.
}
}
}
So here are my questions:
I realy hope you can help me with this, all I found on Google was about running a single method in a class in an external dll (or I was too stupid to see the answer) but found nothing about inherited classes.
Thank you!
Upvotes: 0
Views: 907
Reputation: 1197
First of all the way you defined MyClass
is not abstract, if you need it to be an abstract class then you need to add the abstract modifier keyword, with this in mind i will continue the answer as if MyClass
is a concrete class
Most important: what do I need to do there to create an instance? (The constructor needs a parameter to be passed)
Yes, the constructor of MyClass needs a parameter, and integer to be precise, so you would need to write something like this:
MyClass myclass = new MyClass(1);
How can I check if it was successfull (or better which exceptions means what?)
If you are saying from loading the dll, I can tell you there is a much better way to add a dll to your project, add it as a reference https://learn.microsoft.com/en-us/visualstudio/ide/managing-references-in-a-project?view=vs-2019
What (else) could go wrong (dll not found, dll doesnt contain the class, class in dll doesnt extend MyClass, MyClassInDll has a different constructor than assumed, MyClass has different methods and attributes than version of the MyClass that was used in the dll) and is there anyting I can do?
You cant have two MyClass with different methods and attributes you should only have one and consume that one from both projects (your dll and your main method).
Do methodcalls use a eventually overriden method in the dll? (sould but Im not sure)
You can only override methods if you mark a method as virtual, but I think this question is because you are using 2 MyClass classes which as I said before is a mistake.
I hope with this, im being clear enough but if you need further help please leave a comment.
Upvotes: 1