Dynamically Executing Code in .NET – Compiling C# Code at Runtime

In a recent project, I was confronted with a necessity to change some parts of code algorithms very quickly because government changes. Updating the entire application was not an option, so I decided to implement a feature to allow the application to download small pieces of code that changed frequently to use it.

The application perform some tax math that changes in a monthly basis. Now I can pull only changed code and use it to perform the routine.

To do this I have used the CSharpCodeProvider class from Dotnet framework, that allow us to use C# code as scripting language in my C# application.

In this article I am creating a simple application that have two listbox, the source have all country names and the target will be populated from our script code.

Helper for class for creating instance of code

This class is just a helper to make it easier to instantiate the script code. You just need to pass the code, the class name inside the code and required assemblies.

Main form

In the main form, there is a txtCodeToRun textbox where you can enter the script code to perform the operation. In this example, you don’t need to create the function, just the code that will go inside function.

This is the code for the form:

As you can see, the textbox will contain the function body, and the function will receive as their only parameter, the listbox that contains the list of all countries. So inside the code you will create, you will have access to the listbox with the names of all countries.

Inside the function you can do any operation in the listbox that you wish, but for now, we will only select a few items and return a new List<string> containing the country names to be presented in the target listbox. The function will be used to receive a listbox and return a List<string> with new values to populate the target listbox.

If your script has errors, the helper class will return a class with the errors, that are used to populate the textbox at the bottom of the form with the description of the errors.

Use the following code for the function which will add all countries that starts with “C” to the target listbox :

Dynamic Code Example

Then, you can change the code to retrieve also all countries that starts with “C” and “G” for example:

That is it. A very interesting feature that you can use, to make you application dynamic without changing the entire application.

You can download source code  Here (ZIP file)