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 .


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.

After that we have to load and compile the text file.

And finally call the above static method to load the assembly and run the method.

For a complete example please check the following repository



Write A Comment