How can I allow a user to enter a string into a winforms application and then use reflection to parse that string which can be executed at runtime?
Thanks
How can I allow a user to enter a string into a winforms application and then use reflection to parse that string which can be executed at runtime?
Thanks
Security holes galore, I think, unless you do this with the utmost care! If you really want to do this however, you'll want to look into using the CodeDOM. Since C# is not (yet) a dynamic language, it does not have an eval
feature, and dynamically compiling assemblies with the CodeDOM is the closest you'll get.
For an example, see my answer to this related question, which uses CSharpCodeProvider
along with the CodeDOM to achieve the goal. Beware though, if you want to make your app even reasonably secure, you'll want to run the code with its own AppDomain, and possibly its own process (with some form of IPC).
You can't use reflection to parse a string.
You could use the CSharpCodeProvider class to compile the string (assuming it contains C#) into a temporary assembly. From that you can create objects, locate methods on them and execute them.
This might help you.
TODO list extracted from there:
Transform and wrap user defined method/function body with appropriate method, class, namespace, etc. declarations using the CodeDom (so to get the ready to compile sources either into memory or physical file)
Compile the resulting Dom into the assembly (I'll be using physical files)
Create a separate application domain and load compiled assembly into it.
Extract the generated method from the loaded assembly and invoke it against the execution context (in this case it will be a Window)
Free resources, unload second application domain and perform a temporary files cleanup.
P.s. - DON'T DO IT!