Wednesday, September 28, 2011

C# Runtime Compilation

The .NET framework includes classes that allow the code generator and compiler to be controlled from within an assembly. This allows C# source code, held in a string array, to be compiled at run time and executed using basic reflection techniques.

Runtime Compilation

An interesting aspect of the .NET framework is that it provides a number of classes that allow you to interact with the compiler at run time. This allows you to create C# code in a string and compile it, either storing the resultant assembly in a file or holding it in memory where it can be accessed and executed using reflection. Using the compiler in this manner allows you to provide a means to include complex user customisations. For example, you could allow code to be entered by the user for execution as part of the workflow of your software. You might also use this facility to allow the user to enter C# expressions that are evaluated and used within a report. You may even create your own integrated development environment (IDE).

In this article we will create two examples that compile code to an in-memory assembly at runtime. We will then execute the code to see the results. The first example will be a basic console application where the dynamically compiled source code outputs a message. The second example will allow the user to input an expression to be evaluated and will use the result. We will consider the possibility of the user entering invalid code.

C# Code Compiler

The C# code generator and compiler are made accessible via the CSharpCodeProvider class, which is found in the Microsoft.CSharp namespace:
using Microsoft.CSharp;

To enable dynamic compilation we need to create a CSharpCodeProvider instance. We will later use its methods to generate the object code. Add the following code to the Main method of the console application project.

CSharpCodeProvider provider = new CSharpCodeProvider();

Compiler Parameters

As when using Visual Studio, there are many compiler options that may be configured. Rather than being controlled with multiple properties of the CSharpCodeProvider class, most options are initialised in an instance of the CompilerParameters class, which is found in the System.CodeDom.Compiler namespace:

using System.CodeDom.Compiler;

Read more: BlackWasp
QR: RuntimeCompilation.aspx

Posted via email from Jasper-Net