Dynamic Code Compilation

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.

Lets jump in to 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 complier using CreateCompiler() function of CSharpCodeProvider class and assign to the interface ICodeCompiler.

CSharpCodeProvider codeProvider = new CSharpCodeProvider();
ICodeCompiler icc = codeProvider.CreateCompiler();

Then set the parameters for the compiler using CompilerParameters class. Set parameters like GenerateExecutable, OutputAssembly

 

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");

MOM.JPG

new_app.JPG

The source code is available for download at the top section of this page

Thats all folks!....

Happy coding

Up Next
    Ebook Download
    View all
    Learn
    View all