dotnet-Snippets.com
Add Snippet
Snippets: 137 | Registered User: 138
Main Menu

Home
Random Snippet
Contact Us
Imprint
RSS Feeds

All languages
C#
VB.NET
C++
ASP.NET
Google Ads
Runtime compilation

Author: Michael List
Programming Language: C# Rating:
not yet rated

Views: 939

Description:

Sometimes it can be useful to compile code at runtime and use it afterwards.

Examples would be a script implementation or evaluation of formulas.

The example shown in the snippet is kept simple and only concatenates the input string with the method itself.

This works like a normal compilation, just the completed assembly is directly kept in memory and is accessible via reflection.


Author: Günther Foidl, translation by Michael List




C#
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
using System;
using System.CodeDom.Compiler;
using System.Reflection;
using System.Text;

namespace Compile_code_at_runtime
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.Write("Enter text -> ");
            string textInput = Console.ReadLine();

            Assembly assembly = CompileCode(textInput);
            object o = assembly.CreateInstance("gfoidl.Code.Test");
            Type t = o.GetType();
            MethodInfo mi = t.GetMethod("Result");
            object result = mi.Invoke(o, new object[] { textInput });
            Console.WriteLine(result);

            Console.ReadKey();
        }
        //---------------------------------------------------------------------
        public static Assembly CompileCode(string inputCode)
        {
            CodeDomProvider provider = CodeDomProvider.CreateProvider("CSharp");

            CompilerParameters cp = new CompilerParameters();
            cp.ReferencedAssemblies.Add("system.dll");
            cp.CompilerOptions = "/t:library";
            cp.GenerateInMemory = true;

            StringBuilder sb = new StringBuilder();
            sb.AppendLine(@"using System;");
            sb.AppendLine(@"namespace gfoidl.Code{");
            sb.AppendLine(@"public class Test{");
            sb.AppendLine(@"public string Result(string input){");
            sb.AppendLine(@"return input + ""\t"" + input;");
            sb.AppendLine(@"}}}");

            CompilerResults cr =
                provider.CompileAssemblyFromSource(cp, sb.ToString());

            if (cr.Errors.Count > 0)
            {
                Console.WriteLine(cr.Errors[0].ErrorText);
                return null;
            }

            return cr.CompiledAssembly;
        }
    }
}

This Snippets could be interesting for you:

Poor Excellent
1 2 3 4 5 6 7 8 9 10
Sign in to vote for this snippet.

Comments:
(Please log in to write an comment.)