65.9K
CodeProject is changing. Read more.
Home

Reintroducing my compiler class.

starIconemptyStarIconemptyStarIconemptyStarIconemptyStarIcon

1.00/5 (1 vote)

Jul 22, 2011

LGPL3
viewsIcon

6402

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).

Source code