Click here to Skip to main content
14,691,457 members
Articles » Languages » C# » How To
Posted 8 May 2005


73 bookmarked

Compiling code during runtime

Rate me:
Please Sign up or sign in to vote.
4.71/5 (23 votes)
8 May 2005
This article shows how to compile code during runtime.

Image 1


In some cases it is very useful to compile the source code during execution. For this situation you can use the namespace Microsoft.CSharp. This namespace contains the class CSharpCodeProvider. Using the CSharpCodeProvider you can have access to the C#-compiler. Please note that you can use the compiler with VB.NET also, just use the namespace Microsoft.VisualBasic and the class VBCodeProvider. In Addition to be able to compile your code on the fly you have to add the System.CodeDom and the System.CodeDom.Compiler namespaces.

First step

In this example we will use a RichTextBox in which we'll load some example-code. After that you will be able to compile the code. In this step we'll have a closer look at the source code of the application:

CSharpCodeProvider csp = new CSharpCodeProvider();
ICodeCompiler cc = csp.CreateCompiler();

Using CSharpCodeProvider we gain access to the compiler. Using this compiler we are able to use the csc.exe without any need for the command line. To compile the example-code successfully we have to set some compiler parameters. They include which assemblies should be referred to, where the output assembly has to be stored, which warning level we want to use and some other stuff. The compiler options that we have set are the same as the compiler options you have set using the csc.exe:

CompilerParameters cp = new CompilerParameters();
cp.OutputAssembly = Application.StartupPath + "\\TestClass.dll";
cp.WarningLevel = 3;

cp.CompilerOptions = "/target:library /optimize";
cp.GenerateExecutable = false;
cp.GenerateInMemory = false;

The CompilerParameters class has a property GenerateInMemory. We set this to false because we want to write the assembly to disk and not to memory.

The compilation

After the compilation process we want to know the results, so we create a new instance of the class CompilerResults. CompilerResults needs the parameter tempFiles. These are the files that will be generated by the compiler during compilation. Create an instance of TempFileCollection and set the path to the location where we create the temporary files. If you want to keep the files after compilation set the second parameter of the TempFileCollection to true, otherwise false:

System.CodeDom.Compiler.TempFileCollection tfc = 
                new TempFileCollection(Application.StartupPath, false);
CompilerResults cr  = new CompilerResults(tfc);

Now we can compile our example code. There are different possibilities that are given by the CodeCompiler. In our case we use the method CompileAssemblyFromSource:

cr = cc.CompileAssemblyFromSource(cp, this.rtfCode.Text);
System.Collections.Specialized.StringCollection sc = cr.Output;
foreach (string s in sc) 

After compilation we write the created output to the console. In some cases there may be some compiling errors. You can catch them looking at the property Errors of the CompilerResults object:

if (cr.Errors.Count > 0) 
    foreach (CompilerError ce in cr.Errors) 
        Console.WriteLine(ce.ErrorNumber + ": " + ce.ErrorText);
    MessageBox.Show(this, "Errors occoured", "Errors", 
                    MessageBoxButtons.OK, MessageBoxIcon.Error);
    this.btnExecute.Enabled = false;
    this.btnExecute.Enabled = true;

The execution

Now we've compiled our example code and want to execute it. As you can see within the source code of the sample application, I have created an interface called Command, which includes the method Execute(). Our example code is the implementation of this interface.

To execute the assembly we have to create a new application domain in which the assembly should be loaded. So that we are able to unload the assembly. We use ShadowCopyFiles, because of this we are able to override the original assembly:

AppDomainSetup ads = new AppDomainSetup();
ads.ShadowCopyFiles = "true";
AppDomain newDomain = AppDomain.CreateDomain("newDomain");

We've created the new application domain, and now we want to load the assembly by doing the following lines:

byte[] rawAssembly = loadFile("TestClass.dll");
Assembly assembly = newDomain.Load(rawAssembly, null);

OK, the assembly is loaded, now we want to execute the sample code which will show us a simple MessageBox:

Command testClass = 

After showing the MessageBox we will unload the assembly and the application domain:

testClass = null;
assembly = null;
newDomain = null;


  • 2005/09/05 - Initial article.
  • 2005/10/05 - Added how to catch errors.


This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here


About the Author

Norbert Eder
Team Leader
Austria Austria
Norbert Eder currently works as a .NET software architect at UPPER Network. He writes books and articles about WPF, Silverlight and Windows Phone 7.

For further information see his website or his project site

Comments and Discussions

QuestionStill helpful after 11 years... Pin
szataniel6-Apr-16 2:07
Memberszataniel6-Apr-16 2:07 
GeneralMy vote of 5 Pin
Mahsa Hassankashi8-Mar-15 13:35
mvaMahsa Hassankashi8-Mar-15 13:35 
SuggestionModify the "Load Example" Code Pin
Simone Popolizio7-Feb-15 14:34
MemberSimone Popolizio7-Feb-15 14:34 
Questionsimilar application using web application Pin
Member 103913715-Dec-13 9:20
MemberMember 103913715-Dec-13 9:20 
Questionc++ Pin
Ruth Aanie20-Feb-13 22:52
MemberRuth Aanie20-Feb-13 22:52 
GeneralMy vote of 5 Pin
version_2.013-Jun-11 23:14
Memberversion_2.013-Jun-11 23:14 
GeneralInvalid search path 'C:\\Program Files\\Microsoft Visual Studio .NET\\FrameworkSDK\\Lib\\ Pin
jadoul michel14-Feb-10 10:07
Memberjadoul michel14-Feb-10 10:07 
QuestionHow about Creating assembly without C# file Pin
abcxyz8212-Jun-07 9:29
Memberabcxyz8212-Jun-07 9:29 
GeneralInteracting with the script runner Pin
lshyamal31-May-07 21:48
Memberlshyamal31-May-07 21:48 
Generalcompiling code with assemply Info (in Properties Folder) Pin
abedo19827-May-07 10:37
Memberabedo19827-May-07 10:37 
GeneralcrResults.Errors.Count Pin
nasambur21-Feb-07 0:14
Membernasambur21-Feb-07 0:14 
GeneralRe: crResults.Errors.Count Pin
Norbert Eder21-Feb-07 2:19
MemberNorbert Eder21-Feb-07 2:19 
GeneralRe: crResults.Errors.Count Pin
nasambur21-Feb-07 17:01
Membernasambur21-Feb-07 17:01 
Questioncan a web project use "ReferencedAssemblies.Add("customer.dll")" Pin
wlbkeats8-Dec-06 0:28
Memberwlbkeats8-Dec-06 0:28 
AnswerRe: can a web project use "ReferencedAssemblies.Add("customer.dll")" Pin
Norbert Eder10-Dec-06 20:59
MemberNorbert Eder10-Dec-06 20:59 
QuestionHow to debug the dynamic code ? Pin
sakumira28-Nov-06 18:05
Membersakumira28-Nov-06 18:05 
AnswerRe: How to debug the dynamic code ? Pin
Norbert Eder10-Dec-06 20:46
MemberNorbert Eder10-Dec-06 20:46 
QuestionAJ Pin
almarma413-Nov-06 4:40
Memberalmarma413-Nov-06 4:40 
AnswerRe: AJ Pin
Norbert Eder10-Dec-06 20:48
MemberNorbert Eder10-Dec-06 20:48 
GeneralRe: AJ Pin
zhudexiang9-Mar-07 3:40
Memberzhudexiang9-Mar-07 3:40 
GeneralRe: AJ Pin
André Kurth3-Apr-07 23:03
MemberAndré Kurth3-Apr-07 23:03 
GeneralRe: AJ Pin
BrianARice5-Aug-09 5:18
MemberBrianARice5-Aug-09 5:18 
GeneralRe: AJ Pin
Eranda Ketawalage6-Nov-11 6:23
MemberEranda Ketawalage6-Nov-11 6:23 
QuestionRecompile code Pin
Dr Vespa18-Jan-06 6:15
MemberDr Vespa18-Jan-06 6:15 
AnswerRe: Recompile code Pin
Norbert Eder24-Jan-06 23:11
MemberNorbert Eder24-Jan-06 23:11 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.