Reintroducing my compiler class.
I created a class a couple of years ago which simplifies the CodeCom handling when you want to dynamically create objects in .NET. I got reminded of it when I read a question at stackoverflow.com. The class can be used …Read more »
I created a class a couple of years ago which simplifies the CodeCom handling when you want to dynamically create objects in .NET. I got reminded of it when I read a question at stackoverflow.com.
The class can be used to easily generate .NET (C#) objects by having a class definition in a string variable.
First you have to define an interface (or base class) in your project:
public interface IWorld { string Hello(string value); }
Then you need to add a class to a string variable:
string code = @"namespace MyNamespace { class Temp : IWorld { public string Hello(string value) { return ""World "" + value; } } }";
And let’s generate an object and invoke the method:
Compiler compiler = new Compiler(); //repeat for all types (to automatically add namespaces and assemblies to the CodeDom compiler) compiler.AddType(typeof(string)); // compile the code. Will throw an exception if it do not work. compiler.Compile(code); // create an instance var obj = compiler.CreateInstance<IWorld>(); // and invoke it string result = obj.Hello("World!");
Note that it was a long time ago that I wrote it. The example might not work 100%. (The Compiler class do work, the example might use it incorrectly).