Click here to Skip to main content
15,900,461 members
Articles / All Topics

Reintroducing my compiler class.

Rate me:
Please Sign up or sign in to vote.
1.00/5 (1 vote)
22 Jul 2011LGPL3 6.2K   2
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

License

This article, along with any associated source code and files, is licensed under The GNU Lesser General Public License (LGPLv3)


Written By
Founder 1TCompany AB
Sweden Sweden

Comments and Discussions

 
GeneralMy vote of 1 Pin
BillWoodruff19-May-13 14:50
professionalBillWoodruff19-May-13 14:50 
GeneralRe: My vote of 1 Pin
jgauffin28-May-13 0:07
jgauffin28-May-13 0:07 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.