Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# call a static method at runtime without a build time reference?

Tags:

c#

.net

.net-2.0

I am writing a system in C# .net (2.0). It has a pluggable module sort of architecture. Assemblies can be added to the system without rebuilding the base modules. To make a connection to the new module, I wish to attempt to call a static method in some other module by name. I do not want the called module to be referenced in any manner at build time.

Back when I was writing unmanaged code starting from the path to the .dll file I would use LoadLibrary() to get the .dll into memory then use get GetProcAddress() get a pointer to the function I wished to call. How do I achieve the same result in C# / .NET.

like image 776
Rodney Schuler Avatar asked Sep 10 '09 18:09

Rodney Schuler


1 Answers

After the assembly is loaded using Assembly.LoadFrom(...), you can get the type by name and get any static method:

Type t = Type.GetType(className);

// get the method
MethodInfo method = t.GetMethod("MyStaticMethod",BindingFlags.Public|BindingFlags.Static);

Then you call the method:

method.Invoke(null,null); // assuming it doesn't take parameters
like image 188
Philippe Leybaert Avatar answered Oct 14 '22 01:10

Philippe Leybaert