Welcome to dynamic code compilation. This article throws light on how a code can be built dynamically, compiled, and run. The scenario of dynamic code compilation may arise when you want an application to upgrade (or rewrite) another application.
Let's jump into coding. The namespaces that we are going to use in this project are
- System.CodeDom
- System.CodeDom.Compiler
- Microsoft.CSharp
The System.CodeDom namespace contains classes that can be used to represent the elements and structure of a source code document. The classes in this namespace can be used to model the structure of a source code document that can be output as source code in a supported language using the functionality provided by the System.CodeDom.Compiler namespace.
The Microsoft.CSharp namespace contains classes that support compilation and code generation using the C# language.
At first, we need to instantiate the class CSharpCodeProvider. Then create a compiler using CreateCompiler() function of CSharpCodeProvider class and assign to the interface ICodeCompiler.
- CSharpCodeProvider codeProvider = new CSharpCodeProvider();
- ICodeCompiler icc = codeProvider.CreateCompiler();
- System.CodeDom.Compiler.CompilerParameters parameters = new CompilerParameters();
- parameters.GenerateExecutable = true;
- parameters.OutputAssembly = "Out.exe";
Now declare a String variable and write the source code for the new application/program. Now instantiate CompilerResults class with compiler parameters and the source code as below.
- string sourcecode;
- sourcecode="using System;namespace SampleApp{class Class1{[STAThread] static void Main(string[] args) { Console.WriteLine(\"I am born to live!\");Console.Read(); } }}";
- CompilerResults results = icc.CompileAssemblyFromSource(parameters,sourcecode);
Now the code is compiled. If you want to run the compiled EXE, start the process by
- Process.Start("Out.exe");


That's all folks!....
Happy coding

Naresh M PPosted Aug 27, 2010, 10:36 AM
I am sure the things been changed since it is created. Present day, the ICodeCompiler is obselete and the CSharpCodeCompiler has the method CreateAssembleFromSource. Also, in the above example we would need to use System.Diagnostics to refer to Process class.