To call a static method in different assembly using Reflection in C# and VB.NET you can use the snippet below.

Sample C#

Assembly assembly = Assembly.LoadFile(@"Assembly_Location");   
var type = assembly.Types().FirstOrDefault(x => x.FullName.Contains("MyClassName"));
var constructor = type.GetConstructor(Type.EmptyTypes);

var classObject = constructor.Invoke(new object[] { }); //call parameterless constructor
var classObject = constructor.Invoke(new object[] { param1 }); //call non-parameterless constructor

MethodInfo methodInfo = type.GetMethod("MyMethodName");
methodInfo.Invoke(classObject, new object[] { }); //pass classobject, parameterless method
methodInfo.Invoke(classObject, new object[] { param1 }); //pass classobject, parameterized method

Sample VB.NET

Dim assembly__1 As Assembly = Assembly.LoadFile("Assembly_Location")
Dim type__2 = assembly__1.Types().FirstOrDefault(Function(x) x.FullName.Contains("MyClassName"))
Dim constructor = type__2.GetConstructor(Type.EmptyTypes)

Dim classObject = constructor.Invoke(New Object() {})'call parameterless constructor
Dim classObject = constructor.Invoke(New Object() {param1})'call non-parameterless constructor

Dim methodInfo As MethodInfo = type__2.GetMethod("MyMethodName")
methodInfo.Invoke(classObject, New Object() {})'pass classobject, parameterless method
methodInfo.Invoke(classObject, New Object() {param1})'pass classobject, parameterized method

4 thought on “How to call a non-static method in different assembly using Reflection in C# and VB.NET”

Leave a Reply