Compiling C# code at runtime

Occasionally we might come across a problem which lends itself well to the idea of C# code being compiled at runtime. The .NET Framework includes a mechanism called the Code Document Object Model (CodeDOM) that enables developers of programs that emit source code to generate source code in multiple programming languages at run time, based on a single model that represents the code to render. We can use the CSharpCodeProvider to do exactly this, it can compile some code, create an assembly (in my case in-memory) and then allow us to instantiate the code within that assembly.

Let’s assume that we want a simple method to be compiled from a text file at runtime .

mymethod.txt

C#

1

2

3

4

5

6

7

8

9

10

11

12

13

namespacemyTXTnamespace

{

usingSystem;

classProgram:ScriptExecutor.Interfaces.IScript

{

publicstringRun()

{

Console.WriteLine("Script Program Begin");

return"Returned value from Compiled Script";

}

}

}

We need somehow to load this text file and compile it. For that reason the first step is to inform our program how the structure of this class will be. So we create an interface describing the method of the class.