65.9K
CodeProject is changing. Read more.
Home

Run-Time Code Generation I: Compile C#-Code using Microsoft.CSharp and System.CodeCom.Compiler

starIconstarIconstarIcon
emptyStarIcon
starIcon
emptyStarIcon

3.50/5 (19 votes)

Dec 21, 2005

CPOL

2 min read

viewsIcon

164442

downloadIcon

2614

Compile C#-Code using Microsoft.CSharp and System.CodeCom.Compiler

Introduction

.NET provides mechanisms to compile source code and to use the generated assemblies within an application. Using these features, you can make applications more adaptive and more flexible.

The following article shows how to compile C#-code using Microsoft.CSharp and System.CodeDom.

Necessary Using Statements

Before you start, add the following using statements to your application to ease the use of the namespaces:

using Microsoft.CSharp;
using System.CodeDom.Compiler;

Getting Started

The first step is to instantiate a CSharpCodeProvider and create a compiler with that CodeProvider:

CSharpCodeProvider myCodeProvider = new CsharpCodeProvider();
CodeCompiler myCodeCompiler = myCodeProvider.CreateCompiler();

Setting Parameters

Before starting the compilation, there are various parameters to influence the compilation and its results. An initial parameter is the Reference Assemblies array, which defines the assemblies you can use within your code. Mandatory is the System.dll assembly with the core .NET classes. If you want to use run-time code generation within an ASP.NET application, for example, you have to add System.Web.dll. And of course, you have to set the name of the assembly you want to generate.

String [] referenceAssemblies = {"System.dll"};
string myAssemblyName = „myAssembly.dll“;

With these basic parameters, you can create the CompilerParameters object.

CompilerParameters myCompilerParameters = 
 new CompilerParameters(referenceAssemblies, myAssemblyName);

After that, you can choose if your assembly should be an executable file or not – the default is false, so the compiler creates a class library. Another useful option is to generate the assembly in memory or on hard disk – the default is false, so the compiler stores your assembly in the applications directory.

myCompilerParameters.GenerateExecutable = false;
myCompilerParameters.GenerateInMemory = false;

Compiler Results

After starting the compiler with the CompilerParameters object and of course the C# code you want to compile, you get a CompilerResults object, which helps you to check whether the compilation has been successful or not.

String CsharpSourceCode = „...“;
CompilerResults myCompilerResults = 
 myCodeCompiler.CompileAssemblyFromSource(myCompilerParameters, CSharpSourceCode);

Conclusion

With a few lines of code, you make your application compile source code and create an assembly out of it. But note that you have to provide error-free C# code or check the compiler results before you use the generated assembly.

References