Dynamic code generation
Posted by Igor Moochnick on 01/12/2008
To add to my previous post CodeDom extensions and dynamic LINQ. I’d like to mentions that the same technique can be used to generate/emit a valid compliable code.
Fore example the following snippet:
1: var c = new CodeDom();
2: c.AddNamespace("Samples").Imports("System")
3: .AddClass(
4: c.Class("TestClass")
5: .AddMethod(c.Method("PrintTest", "Console.WriteLine(\"Hello world !\");")));
6:
7: string s = c.GenerateCode();
will generate the following code, which, at the end, can be written to a file or compiled in-memory:
1: //------------------------------------------------------------------------------
2: // <auto-generated>
3: // This code was generated by a tool.
4: // Runtime Version:2.0.50727.1433
5: //
6: // Changes to this file may cause incorrect behavior and will be lost if
7: // the code is regenerated.
8: // </auto-generated>
9: //------------------------------------------------------------------------------
10:
11: namespace Samples {
12: using System;
13:
14:
15: public class TestClass
16: {
17: public static void PrintTest()
18: {
19: Console.WriteLine(\"Hello world!\");
20: }
21: }
22: }
So, unleash your imagination!
[The full source code with tests/examples you can find, as usual, on my web site: http://igor.moochnick.googlepages.com]



