I am trying to add some specific modular functonality to my application, I need users to be able to create their own classes and then have them imported into the program at runtime, these classes will follow a specific template so I can call functions within their new class.
For example, a class could be: http://pastebin.com/90NTjia9
I would compile the class and then execute doSomething();
How would I achieve this in C#?
If your users have the necessary tools (such as Visual Studio, which they really should have if they’re writing C# classes), they can supply you with a DLL, which you can then load dynamically:
The T generic parameter is there so that you can pass an
abstractclassorinterfaceto cast the type instance to:Your users inherit from this interface when they write their own class:
This allows you to retain type safety and call the class methods directly, rather than relying on Reflection to do so.
If you really want your users to provide C# source, you can compile their class at runtime like this:
Then, you just substitute the resulting assembly in the
CreateInstancecode above, instead of the externally-loaded assembly. Note that your users will still need to provide the appropriateusingstatements at the top of their class.There are also places on the Internet that explain how to get an
Eval()function in C#, in case you don’t really need a full-blown class.