Click here to Skip to main content
13,055,047 members (60,176 online)
Click here to Skip to main content
Add your own
alternative version

Tagged as

Stats

4.7K views
Posted 22 Jul 2011

Reintroducing my compiler class.

, 22 Jul 2011
Rate this:
Please Sign up or sign in to vote.
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)

Share

About the Author

jgauffin
Founder Gauffin Interactive AB
Sweden Sweden
Founder of OneTrueError, a .NET service which captures, analyzes and provide possible solutions for exceptions.

blog | twitter

You may also be interested in...

Comments and Discussions

 
GeneralMy vote of 1 Pin
BillWoodruff19-May-13 14:50
memberBillWoodruff19-May-13 14:50 
GeneralRe: My vote of 1 Pin
jgauffin28-May-13 0:07
memberjgauffin28-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.

Permalink | Advertise | Privacy | Terms of Use | Mobile
Web01 | 2.8.170713.1 | Last Updated 22 Jul 2011
Article Copyright 2011 by jgauffin
Everything else Copyright © CodeProject, 1999-2017
Layout: fixed | fluid