Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I load a Class Library DLL at runtime and run a class function using VB.NET?

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?

like image 876
Samik Sengupta Avatar asked Sep 15 '25 09:09

Samik Sengupta


1 Answers

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.

like image 171
Heinzi Avatar answered Sep 18 '25 08:09

Heinzi