How do I load a Class Library DLL at runtime and run a class function using VB.NET?
.net-assembly, dll, runtime, vb.net
Solution
I suggest to make `DoIt` shared, since it does not require class state:
Public Class SomeClass
Public Shared Function DoIt() as String
Return "Do What?"
End Function
End Class
Then calling it is easy:
' Loads SomeClass.dll
Dim asm = Assembly.Load("SomeClass")
' Replace the first SomeClass with the base namespace of your SomeClass assembly
Dim type = asm.GetType("SomeClass.SomeClass")
Dim returnValue = DirectCast(type.InvokeMember("DoIt", _
BindingFlags.InvokeMethod | BindingFlags.Static, _
Nothing, Nothing, {}),
String)
If you cannot make the method shared, you can create an instance of your class with Activator.CreateInstance and pass it as a parameter to Type.InvokeMember.
All my code examples assume Option Strict On and Option Infer On.
Problem
Say I've a class like this inside a class library project called SomeClass- ``` Public Class SomeClass Public Function DoIt() as String Return "Do What?" End Function End Class ``` I get a `SomeClass.dll` which I want to load at runtime from another Windows Forms Application, and then have it call the `DoIt()` function and show it's value in a messagebox or something. How do I do that?