In a previous blog I explored how to create a dynamic compiler. In this blog I’ll explore how to create an evaluator that aids in the compilation of classes. It will take care of the ceremony needed to wrap the code into a class, compile it and retrieve the result.

The Evaluator class

The basic idea is to feed the evaluator the code and to execute it by calling Run. I’ve added some comments to the class to explain how it works.

A script doesn’t have to produce anything, that’s why the generated class returns null by default. If the specified script does not have to have a return. The script also adds an extra ‘;’ to the script.

Hello world script

So let’s create a small script that prints Hello World! 10 times:

The following example shows how to return a string and print it:

Evaluation with a special class

What if you want to interact with the object that was compiled? That’s possible. First create a generic evaluator:

Next create an abstract class that defines the interaction. This class needs to implement IProducer:

Let’s see it in action:

So that’s it. Happy coding!